在不重启服务器的情况下重新填充Django ChoiceField

时间:2011-10-25 14:19:28

标签: django django-admin django-forms

我有一个简单的表单,用户可以从选择域中选择一个部门。

这是我的表格:

class NewDealForm1(forms.Form):
        department = forms.ChoiceField(choices = map(lambda x:('%s'% x.id, '%s' % x.title),Department.objects.all()))

每当我从管理员添加新部门时,除非我重新启动服务器,否则我的选择字段不显示新部门。

如何在不重新启动服务器的情况下显示所有部门?

2 个答案:

答案 0 :(得分:4)

沃尔夫的回答是正确的。

但是要直接回答你的问题(“重新启动Django ChoiceField而不重启服务器”),你需要在表单构造函数中设置选项。以下是动态信用卡年度选择的示例。

class NewDealForm1(forms.Form):
    year = forms.ChoiceField(choices=[]))

    def __init__(self, *args, **kwargs):
        super(NewDealForm, self).__init__(*args, **kwargs)
        year = datetime.date.today().year
        self.fields['year'].choices = [(x, x) for x in range(year, year+10)]

答案 1 :(得分:3)

您应该尝试使用forms.ChoiceField直接接收查询集,而不是使用forms.ModelChoiceField

文档:https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield

实施例

class NewDealForm1(forms.Form):
    department = forms.ModelChoiceField(queryset=Department.objects.all()))