Django - 将选择字段添加到django admin list_filter

时间:2017-09-24 21:42:54

标签: django django-admin django-admin-actions

这是我的django管理类之一:

class InactiveSiteAdmin(SiteAdmin):
    change_list_template = 'admin/change_list_inactive.html'
    list_display = ('is_active', 'thumb', 'name', 'show_url', 'get_desc', 
        'keywords','category', 'subcategory', 'category1', 'subcategory1', 
        'group')
    fields = ('name', 'url', 'id', 'category', 'subcategory', 'category1',
          'subcategory1', 'description',
          'keywords', 'date', 'group', 'user', 'is_active', 'date_end',)
    readonly_fields = ('date', 'date_end', 'id')
    list_display_links = ('name',)
    actions = [activate_sites, activate_sites1, ]

    def get_queryset(self, request):
        return Site.objects.filter(is_active=False)

    def response_change(self, request, obj):
        return redirect('/admin/mainapp/site/{}/change/'.format(obj.id))

    def has_add_permission(self, request):
       return False

“activate_sites”操作用于接受所选对象(使其可见)以及向obj.email发送确认电子邮件(所选对象的电子邮件字段)。我想在list_display中添加另一个字段 - 例如“email_text”,其中超级用户将选择正确的文本消息(使用选择字段)。可能吗?我有3个对象。我想有机会激活所有3个对象,并为每个对象选择不同的文本消息。

我尝试添加这样的东西:

def email_send_field(self, request):
    MY_CHOICES = (
        ('A', 'Choice A'),
        ('B', 'Choice B'),
    )

    return(forms.ChoiceField(choices=MY_CHOICES))

但我在list_display中得到了“”。

1 个答案:

答案 0 :(得分:1)

您可以使用format_html方法插入自定义html并在POST数据中获取所选值。

请注意为每个select元素生成唯一的名称。

在此示例中,它使用对象主键:

from django.utils.html import format_html

MY_CHOICES = (
    ('msg1', 'Hello'),
    ('msg2', 'Hi'),
)

class InactiveSiteAdmin(SiteAdmin):
    list_display = list_display = ( ...,  'show_select')
     actions = ['send_email']

    def show_select(self, obj):
        html_select = "<select name='dropdown-obj-"+str(obj.pk)+"'>"
        for option in MY_CHOICES:
            html_select += "<option value='{}'>{}</option>".format(option[1], option[0])
        html_select += "</select> "

        return format_html(html_select)

    def send_email(self, request, queryset):
        for obj in queryset:
            obj_msg = request.POST['dropdown-obj-'+str(obj.pk)]
            #do something with the custom message
相关问题