[Fixed]-Add context to every Django Admin page

9👍

Found the solution, url registration has to be:

urlpatterns = [
    url(r'^admin/', admin.site.urls, {'extra_context': {'mycontext': '123'}}),
]

Its a context dictionary inside of a dictionary with 'extra_context' as a key.

5👍

Another technique, more complex but allows different context per request (probably unavailable at OP time):

my_project/admin.py (create if missing)

from django.contrib import admin
from django.contrib.admin.apps import AdminConfig


class MyAdminConfig(AdminConfig):
    default_site = 'my_project.admin.MyAdminSite'


class MyAdminSite(admin.AdminSite):
    def each_context(self, request):
        context = super().each_context(request)
        context.update({
            "whatever": "this is",
            "just a": "dict",
        })
        return context

settings.py

INSTALLED_APPS = [
    ...
    'my_project.admin.MyAdminConfig',  # replaces 'django.contrib.admin'
    ...

The replace / extend admin class code is taken from the official docs except this is all in one file.

👤frnhr

Leave a comment