How can I add a button into django admin change list view page

后端 未结 2 1988
广开言路
广开言路 2020-12-04 18:24

I would like to add a button next to \"add\" button in list view in model for my model and then create a view function where I will do my stuff and then redirect user back t

2条回答
  •  不知归路
    2020-12-04 18:53

    Here is another solution , without using of jQuery (like one provided by allcaps). Also this solution provides object's pk with more intuitive way :)

    I'll give my source code based on that link (follow link above for more info):

    I have an app Products with model Product. This code adds button "Do Evil", which executes ProductAdmin.do_evil_view()

    File products/models.py:

    class ProductAdmin(admin.ModelAdmin):   
        def get_urls(self):
            urls = super().get_urls()
            my_urls = patterns('',
                (r'^(?P\d+)/evilUrl/$', self.admin_site.admin_view(self.do_evil_view))
            )
            return my_urls + urls
    
        def do_evil_view(self, request, pk):
            print('doing evil with', Product.objects.get(pk=int(pk)))
            return redirect('/admin/products/product/%s/' % pk)
    

    self.admin_site.admin_view is needed to ensure that user was logged as administrator.

    And this is template extention of standard Django admin page for changing entry:
    File: {template_dir}/admin/products/product/change_form.html

    In Django >= 1.8 (thanks to @jenniwren for this info):

    {% extends "admin/change_form.html" %}
    {% load i18n %}
    {% block object-tools-items %}
        {{ block.super }}
        
  • {% trans "Do Evil" %}
  • {% endblock %}

    If your Django version is lesser than 1.8, you have to write some more code:

    {% extends "admin/change_form.html" %}
    {% load i18n %}
    {% block object-tools %}
    {% if change %}{% if not is_popup %}
    
    {% endif %}{% endif %}
    {% endblock %}  
    

提交回复
热议问题