如何覆盖Django admin的观点?

时间:2022-12-02 19:18:33

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

我想在默认的Django管理员中添加一个上传按钮,如下所示:

如何覆盖Django admin的观点?

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?

为此,我重写了admin / index.html模板以添加按钮,但是如何覆盖管理视图以便处理它?

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

我想要实现的是在上传文件后显示成功消息或错误消息。

1 个解决方案

#1


16  

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):

索引视图位于AdminSite实例上。要覆盖它,您必须创建一个自定义AdminSite子类(即,不再使用django.contrib.admin.site):

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

您可能希望在以下位置引用原始方法: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来注册您的模型。

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

您可以在以下网址找到更多详细信息和示例:https://docs.djangoproject.com/en/dev/ref/contrib/admin/#adminsite-objects

#1


16  

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):

索引视图位于AdminSite实例上。要覆盖它,您必须创建一个自定义AdminSite子类(即,不再使用django.contrib.admin.site):

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

您可能希望在以下位置引用原始方法: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来注册您的模型。

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

您可以在以下网址找到更多详细信息和示例:https://docs.djangoproject.com/en/dev/ref/contrib/admin/#adminsite-objects