Django + Forms:ChoiceField的动态选择

时间:2014-03-07 16:42:38

标签: django forms

我正在尝试为ChoiceField创建一个动态选项列表,但我似乎无法调用请求。这是代码:

错误:

AttributeError: 'CreationForm' object has no attribute 'request'

表单

class FooForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        bars = self.request.session['bars']
        foo_list = []
        for bar in bars:
            foo_list.append((bar['id'], bar['name']),)
        self.fields['foo'].choices = foo_list
    foo = forms.ChoiceField(choices=foo_list, required=True)

2 个答案:

答案 0 :(得分:18)

为什么不在实例化表单时从视图中传递选项?

e.g。

形式:

class FooForm(forms.Form):
    def __init__(self, foo_choices, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        self.fields['foo'].choices = foo_choices

    foo = forms.ChoiceField(choices=(), required=True)

查看:

... 
bars = request.session['bars']
foo_list = []
for bar in bars:
    foo_list.append((bar['id'], bar['name']),)
form = FooForm(foo_list)
...

答案 1 :(得分:0)

要处理is_valid()行动的验证,我认为这样可行

class FooForm(forms.Form):
    def __init__(self, foo_choices, *args, **kwargs):
        self.base_fields['foo'].choices = foo_choices
        super(FooForm, self).__init__(*args, **kwargs)

    foo = forms.ChoiceField(choices=(), required=True)

上述代码未经测试