Skip to content

[BUG] Django Ninja docs fails when django.contrib.auth is not in INSTALLED_APPS #1438

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
devjerry0 opened this issue Apr 7, 2025 · 2 comments

Comments

@devjerry0
Copy link

devjerry0 commented Apr 7, 2025

Describe the bug
When trying to access the Django Ninja auto-generated docs at /api/v1/docs, an error occurs if django.contrib.auth is not in INSTALLED_APPS:

This is problematic for projects that intentionally avoid using Django's auth system:

  1. It forces including django.contrib.auth in INSTALLED_APPS even when not using Django's auth system
  2. This adds unwanted database tables or requires workarounds
  3. The only current alternative is to disable docs completely with docs_url=None or create a custom view.

Expected Behavior

Django Ninja's documentation should work without requiring django.contrib.auth to be in INSTALLED_APPS. Ideally:

  1. Not depend on Django's auth system for docs rendering
  2. Provide a parameter/flag to disable auth or alternative docs viewer that doesn't require auth

Steps to Reproduce

Setup

# settings.py
INSTALLED_APPS = [
    # "django.contrib.auth",  # Not included
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # Your other apps...
]

# api.py
from ninja import NinjaAPI

api = NinjaAPI(
    title="My API",
    version="1.0.0",
    # Using default docs settings
)

@api.get("/hello")
def hello(request):
    return {"message": "Hello world"}

# urls.py
from django.urls import path
from .api import api

urlpatterns = [
    path("api", api.urls),
]`

You can quickly get this by runninng in ./manage.py shell this line:
import django; import pydantic; import ninja; django.__version__; ninja.__version__; pydantic.__version__

Versions (please complete the following information):

  • Python version: 3.12+
  • Django version: 5.1+
  • Django-Ninja version: 1.3+
  • Pydantic version: latest
@vitalik
Copy link
Owner

vitalik commented Apr 7, 2025

Hi @devjerry0 would be nice if you provide a traceback,

I assume you have something like this:

...
  File "/private/tmp/dislip_contradictiveness/.venv/lib/python3.12/site-packages/django/template/context.py", line 259, in bind_template
    context = processor(self.request)
              ^^^^^^^^^^^^^^^^^^^^^^^
  File "/private/tmp/dislip_contradictiveness/.venv/lib/python3.12/site-packages/django/contrib/auth/context_processors.py", line 60, in auth
    from django.contrib.auth.models import AnonymousUser
  File "/private/tmp/dislip_contradictiveness/.venv/lib/python3.12/site-packages/django/contrib/auth/models.py", line 39, in <module>
    class Permission(models.Model):
  File "/private/tmp/dislip_contradictiveness/.venv/lib/python3.12/site-packages/django/db/models/base.py", line 136, in __new__
    raise RuntimeError(
RuntimeError: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

if so you need to remove auth context processor from TEMPLATE settings:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                # 'django.contrib.auth.context_processors.auth',   # <-------------- !!!!!!!!!!!!!!!!
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

@devjerry0
Copy link
Author

devjerry0 commented Apr 7, 2025

@vitalik thanks for the quick response!
jeez of course I forgot the template config, we don't use templates apart from the openapi docs.

Thank you, worked!
Want me to create a pr on the ninja docs ?

btw my workaround was creating a hacky custom view ^^

import json

from typing import TYPE_CHECKING, Any

from django.http import HttpRequest, HttpResponse
from ninja import NinjaAPI
from ninja.openapi.docs import Swagger

if TYPE_CHECKING:
    from ninja import NinjaAPI

CSRF_TEMPLATE = """{% if add_csrf %}
        configObject.requestInterceptor = (req) => {
            req.headers['X-CSRFToken'] = "{{csrf_token}}";
            return req;
        };
    {% endif %}"""


class CustomDocsViewer(Swagger):
    """Custom documentation viewer that bypasses Django auth.

    This viewer extends the default Swagger viewer but removes the authentication
    requirement by bypassing Django's auth system and CSRF protection.
    """

    def render_page(self, request: HttpRequest, api: "NinjaAPI", **kwargs: Any) -> HttpResponse:
        """Render the API documentation without using Django auth."""
        self.settings["url"] = self.get_openapi_url(api, kwargs)

        with open(self.template_cdn) as f:
            html = (
                f.read()
                .replace("{{ api.title }}", getattr(api, "title", "API Documentation"))
                .replace("{{ swagger_settings | safe }}", json.dumps(self.settings, indent=1))
                .replace(CSRF_TEMPLATE, "")
            )

        return HttpResponse(html)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants