如何覆盖Django管理员的意见? [英] How to override Django admin's views?

查看:125
本文介绍了如何覆盖Django管理员的意见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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





为此,我会覆盖admin / index.html模板添加按钮,但是如何我覆盖管理视图以处理它?<​​/ p>

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

解决方案

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

 从django.contrib.admin导入AdminSite 
from django.views.decorators.cache import never_cache

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

您可能需要参考原始方法: https://github.com/django/django/blob/1.4.1/django/contrib/admin/sites.py



然后,您创建一个此类的实例,并使用此实例,而不是 admin.site 注册你的模型。

  admin_site = MyAdminSite()

然后,稍后:

 从某处导入admin_site 

MyModelAdmin(ModelAdmin):
...

admin_site.register(MyModel,MyModelAdmin)

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


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

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.

解决方案

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

这篇关于如何覆盖Django管理员的意见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆