22

例如(不是这种情况,只是为了说明)如果我想添加一个操作以将所选项目中的特定字段设置为 X。是否可以添加一个操作以允许输入 X 而不是硬编码?

4

2 回答 2

19

请参阅:提供中间页面的操作

您不能直接从更改列表页面执行此操作,但在中间页面上,您可以有一个允许用户输入值的表单,然后将该值用于操作。

于 2012-08-01T17:53:39.933 回答
10

It is possible with Django 1.5, though its a little hackish. I am not sure with what other older Django versions it's possible.

You write your own ModelAdmin subclass. ModelAdmin has an attribute called action_form which determines the form shown before Go button on changelist page. You can write your own form, and set it as action_form on your ModelAdmin subclass.

from django import forms
from django.contrib.admin.helpers import ActionForm
# ActionForm is the default form used by Django
# You can extend this class

class XForm(ActionForm):
    x_field = forms.CharField()
    

class YourModelAdmin(admin.ModelAdmin):
    action_form = XForm

With these changes, you will have a CharField, where you can put value for X.

And use x_field in your action function.

def set_x_on_objects(modeladmin, request, queryset):
    for obj in queryset:
        obj.something = request.POST['x_field']
    # do whatever else you want

class YourModelAdmin(admin.ModelAdmin):
    action_form = XForm
    actions = [set_x_on_objects]
于 2014-08-01T12:13:35.643 回答