How to override Django admin's views?

jul picture jul · Sep 7, 2012 · Viewed 13.9k times · Source

I want to add an upload button to the default Django admin, as shown below:

enter image description here

To do so I overrode the admin/index.html template to add the button, but how can I override the admin view in order to process it?

What I want to achieve is to display a success message, or the error message, once the file is uploaded.

Answer

Chris Pratt picture Chris Pratt · Sep 7, 2012

The index view is on the AdminSite instance. To override it, you'll have to create a custom AdminSite subclass (i.e., not using django.contrib.admin.site anymore):

from django.contrib.admin import AdminSite
from django.views.decorators.cache import never_cache

class MyAdminSite(AdminSite):
    @never_cache
    def index(self, request, extra_context=None):
        # do stuff

You might want to reference the original method at: https://github.com/django/django/blob/1.4.1/django/contrib/admin/sites.py

Then, you create an instance of this class, and use this instance, rather than admin.site to register your models.

admin_site = MyAdminSite()

Then, later:

from somewhere import admin_site

class MyModelAdmin(ModelAdmin):
    ...

admin_site.register(MyModel, MyModelAdmin)

You can find more detail and examples at: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#adminsite-objects