2011-10-25 111 views
2

我有一个简单的表单,用户可以从选择字段中选择一个部门。重新生成Django ChoiceField而不重新启动服务器

这是我的形式:

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

每当我从管理员添加一个新部门,除非我重新启动我的服务器我choicefield不显示新的部门。

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

回答

4

Wolph的答案是正确的。

但要直接回答您的问题(“重新填充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)] 
相关问题