Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add context to every Django Admin page

How do I add extra context to all admin webpages?

I use default Django Admin for my admin part of a site.

Here is an url entry for admin:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

And my apps register their standard view models using:

admin.site.register(Tag, TagAdmin)

My problem, is that I want to display an extra field in admin template header bar and I have no idea how to add this extra context.

My first bet was adding it in url patterns like below:

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

But that gives an error:

TypeError at /admin/tickets/event/4/change/

change_view() got an unexpected keyword argument 'mycontext'

Can you give any suggestion? I really do not want to modify every AdminModel class I have to insert this context, as I need it on every admin page.

Thanks.

like image 350
alandarev Avatar asked Sep 13 '16 18:09

alandarev


People also ask

Can we customize Django admin panel?

We have a lot of tools in Django to customize it to our own needs and in this article, we'll learn how to customize the admin interface and add multiple features: Let's setup your project, add models into models.py and register your models.

How do I add an admin to text in Django?

help_text = "Please use the following format: <em>YYYY-MM-DD</em>." After running makemigrations and migrate on Django and rendering the above model, let us check if something has happened to our field in Django admin Interface. You can see extra text added at the bottom of the field.


1 Answers

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.

like image 153
frnhr Avatar answered Oct 07 '22 14:10

frnhr