18

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.

jul
  • 36,404
  • 64
  • 191
  • 318
  • See [this FAQ on Django wiki](https://code.djangoproject.com/wiki/NewformsHOWTO#Q:HowcanIpassextracontextvariablesintomyindexpage). No need to override/subclass `AdminSite`. – xyres Mar 16 '16 at 15:28

1 Answers1

25

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

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • 1
    Ok Thank you. There is no other way to achieve this? For instance by creating a new module (something like the sidebar)? – jul Sep 07 '12 at 16:43
  • That sidebar itself is populated by context added via the index view. The only way to add more context is to override the index view, and the only way to do that is to subclass `AdminSite`. – Chris Pratt Sep 07 '12 at 19:02
  • Do you recommend doing this in a separate app? – Shawn May 09 '13 at 21:26
  • Is this also the way to add another link among `'Add'` and `'Change'`, that can be found with the model name? I'm planning to add a link `'View only'` along with this. thx – Charlesliam Jan 26 '14 at 02:19
  • @Chris. I have so many models in my project..Do I need to register all the models to this new admin? – user1050619 Oct 26 '16 at 15:21
  • This helped me out as well using Django 1.10. My use case i had to choose a different template/view according to the user type. So if it was a certain king i would redirect it to the proper view or load the default index template. Thanks – psychok7 Feb 28 '17 at 14:24