如何在Django管理站点中添加“添加用户”按钮旁边的按钮

时间:2023-01-19 16:49:39

I am working on Django Project where I need to extract the list of user to excel from the Django Admin's Users Screen. I added actions variable to my Sample Class for getting the CheckBox before each user's id.

我正在开发Django项目,我需要从Django Admin的用户屏幕中提取用户列表到excel。我在我的Sample Class中添加了actions变量,以便在每个用户的id之前获取CheckBox。

class SampleClass(admin.ModelAdmin):
    actions =[make_published]

Action make_published is already defined. Now I want to append another button next to Add user button as shown in fig. 如何在Django管理站点中添加“添加用户”按钮旁边的按钮. But I dont know how can I achieve this this with out using new template. I want to use that button for printing selected user data to excel. Thanks, please guide me.

动作make_published已经定义。现在我想在Add user按钮旁边添加另一个按钮,如图2所示。 。但我不知道如何在不使用新模板的情况下实现这一目标。我想使用该按钮将所选用户数据打印到excel。谢谢,请指导我。

3 个解决方案

#1


30  

  1. Create a template in you template folder: admin/YOUR_APP/YOUR_MODEL/change_list.html
  2. 在模板文件夹中创建模板:admin / YOUR_APP / YOUR_MODEL / change_list.html
  3. Put this into that template

    把它放到那个模板中

    {% extends "admin/change_list.html" %}
    {% block object-tools-items %}
    
        {{ block.super }}
    
        <li>
            <a href="export/" class="grp-state-focus addlink">Export</a>
        </li>
    
    {% endblock %}
    
  4. Create a view function in YOUR_APP/admin.py and secure it with annotation

    在YOUR_APP / admin.py中创建一个视图函数,并使用注释对其进行保护

    from django.contrib.admin.views.decorators import staff_member_required
    
    @staff_member_required
    def export(self, request):
    
        ... do your stuff ...
    
        return HttpResponseRedirect(request.META["HTTP_REFERER"])
    
  5. Add new url into YOUR_APP/admin.py to url config for admin model

    将新网址添加到YOUR_APP / admin.py到管理模型的url配置

    from django.conf.urls import patterns, include, url
    
    class YOUR_MODELAdmin(admin.ModelAdmin):
    
        ... list def stuff ...
    
        def get_urls(self):
            urls = super(MenuOrderAdmin, self).get_urls()
            my_urls = patterns("",
                url(r"^export/$", export)
            )
            return my_urls + urls
    

Enjoy ;)

请享用 ;)

#2


1  

Though other answers are entirely valid, I think it is important to note that it is absolutely not necessary to add a button to get such behavior. You can use admin actions, as you did for the make_published action.

虽然其他答案完全有效,但我认为重要的是要注意,绝对没有必要添加按钮来获取此类行为。您可以像使用make_published操作一样使用管理操作。

This as the advantage of not requiring to override any template, and thus prevent from potential troubles when upgrading django version (as admin templates may change, and changes might not be "compatible" with the way you overrode it).

这样做的好处是不需要覆盖任何模板,从而防止在升级django版本时出现潜在的麻烦(因为管理模板可能会更改,并且更改可能与您覆盖它的方式“兼容”)。

import csv

from django.http import HttpResponse
from django.utils import timezone

def export_as_csv(modeladmin, request, queryset):
    opts = modeladmin.model._meta
    filename = format(timezone.now(), "{app}_{model}-%Y%m%d_%H%M.csv").format(
        app=opts.app_label, model=opts.model_name)

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)

    writer = csv.writer(response)
    field_names = [f.get_attname() for f in opts.concrete_fields]
    writer.writerow(field_names)
    for obj in queryset.only(*field_names):
        writer.writerow([str(getattr(obj, f)) for f in field_names])

    return response

Admin actions are made for this, adding a custom button is one step closer to "over-customization", which means it's probably time to write your own views.

为此进行了管理操作,添加自定义按钮更接近“过度定制”,这意味着可能是编写自己的视图的时候了。

The admin has many hooks for customization, but beware of trying to use those hooks exclusively. If you need to provide a more process-centric interface that abstracts away the implementation details of database tables and fields, then it’s probably time to write your own views.

管理员有许多用于自定义的钩子,但要注意尝试专门使用这些钩子。如果您需要提供一个更加以流程为中心的接口来抽象出数据库表和字段的实现细节,那么可能是时候编写自己的视图了。

Quote from the introduction paragraph of Django Admin's documentation

引自Django Admin文档的介绍段落

#3


0  

The easy and accepted way is to override the template.

简单且可接受的方式是覆盖模板。

If you don't want to mess with the Django templates, you could add a Media class to your admin and add some javascript to create the button although I think creating elements with javascript is a bit nasty and should be avoided.

如果你不想搞乱Django模板,你可以向你的管理员添加一个Media类并添加一些javascript来创建按钮,虽然我认为用javascript创建元素有点讨厌,应该避免。

#1


30  

  1. Create a template in you template folder: admin/YOUR_APP/YOUR_MODEL/change_list.html
  2. 在模板文件夹中创建模板:admin / YOUR_APP / YOUR_MODEL / change_list.html
  3. Put this into that template

    把它放到那个模板中

    {% extends "admin/change_list.html" %}
    {% block object-tools-items %}
    
        {{ block.super }}
    
        <li>
            <a href="export/" class="grp-state-focus addlink">Export</a>
        </li>
    
    {% endblock %}
    
  4. Create a view function in YOUR_APP/admin.py and secure it with annotation

    在YOUR_APP / admin.py中创建一个视图函数,并使用注释对其进行保护

    from django.contrib.admin.views.decorators import staff_member_required
    
    @staff_member_required
    def export(self, request):
    
        ... do your stuff ...
    
        return HttpResponseRedirect(request.META["HTTP_REFERER"])
    
  5. Add new url into YOUR_APP/admin.py to url config for admin model

    将新网址添加到YOUR_APP / admin.py到管理模型的url配置

    from django.conf.urls import patterns, include, url
    
    class YOUR_MODELAdmin(admin.ModelAdmin):
    
        ... list def stuff ...
    
        def get_urls(self):
            urls = super(MenuOrderAdmin, self).get_urls()
            my_urls = patterns("",
                url(r"^export/$", export)
            )
            return my_urls + urls
    

Enjoy ;)

请享用 ;)

#2


1  

Though other answers are entirely valid, I think it is important to note that it is absolutely not necessary to add a button to get such behavior. You can use admin actions, as you did for the make_published action.

虽然其他答案完全有效,但我认为重要的是要注意,绝对没有必要添加按钮来获取此类行为。您可以像使用make_published操作一样使用管理操作。

This as the advantage of not requiring to override any template, and thus prevent from potential troubles when upgrading django version (as admin templates may change, and changes might not be "compatible" with the way you overrode it).

这样做的好处是不需要覆盖任何模板,从而防止在升级django版本时出现潜在的麻烦(因为管理模板可能会更改,并且更改可能与您覆盖它的方式“兼容”)。

import csv

from django.http import HttpResponse
from django.utils import timezone

def export_as_csv(modeladmin, request, queryset):
    opts = modeladmin.model._meta
    filename = format(timezone.now(), "{app}_{model}-%Y%m%d_%H%M.csv").format(
        app=opts.app_label, model=opts.model_name)

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)

    writer = csv.writer(response)
    field_names = [f.get_attname() for f in opts.concrete_fields]
    writer.writerow(field_names)
    for obj in queryset.only(*field_names):
        writer.writerow([str(getattr(obj, f)) for f in field_names])

    return response

Admin actions are made for this, adding a custom button is one step closer to "over-customization", which means it's probably time to write your own views.

为此进行了管理操作,添加自定义按钮更接近“过度定制”,这意味着可能是编写自己的视图的时候了。

The admin has many hooks for customization, but beware of trying to use those hooks exclusively. If you need to provide a more process-centric interface that abstracts away the implementation details of database tables and fields, then it’s probably time to write your own views.

管理员有许多用于自定义的钩子,但要注意尝试专门使用这些钩子。如果您需要提供一个更加以流程为中心的接口来抽象出数据库表和字段的实现细节,那么可能是时候编写自己的视图了。

Quote from the introduction paragraph of Django Admin's documentation

引自Django Admin文档的介绍段落

#3


0  

The easy and accepted way is to override the template.

简单且可接受的方式是覆盖模板。

If you don't want to mess with the Django templates, you could add a Media class to your admin and add some javascript to create the button although I think creating elements with javascript is a bit nasty and should be avoided.

如果你不想搞乱Django模板,你可以向你的管理员添加一个Media类并添加一些javascript来创建按钮,虽然我认为用javascript创建元素有点讨厌,应该避免。