Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override Django admin's views?

Tags:

django

admin

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.

like image 848
jul Avatar asked Sep 07 '12 15:09

jul


People also ask

Can we customize Django admin template?

The Django admin is a powerful built-in tool giving you the ability to create, update, and delete objects in your database using a web interface. You can customize the Django admin to do almost anything you want.

How do I override a field in Django admin?

The way to override fields is to create a Form for use with the ModelAdmin object. This didn't work for me, you need to pass an instance of the widget, rather than the class. The instance worked perfectly, though. I typically would create custom admin forms in the admin.py and not mix them in with forms.py.

How do I override Django admin base in HTML?

To override the default template you first need to access the template you want to modify from the django/contrib/admin/templates/admin directory. Let's say we want to change base. html – to do so, we would copy that file and paste it into the templates/admin directory in our project.

How do I change the administrator name in Django?

To change the admin site header text, login page, and the HTML title tag of our bookstore's instead, add the following code in urls.py . The site_header changes the Django administration text which appears on the login page and the admin site. The site_title changes the text added to the <title> of every admin page.


1 Answers

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

like image 188
Chris Pratt Avatar answered Oct 23 '22 03:10

Chris Pratt