如何从视图中将值传递给Django Form的init方法?

时间:2015-01-28 23:31:26

标签: django forms views init choicefield

forms.py

class AddDuration(forms.Form):

    def __init__(self, *args, **kwargs): 
        super(AddDuration, self).__init__(*args, **kwargs)
        // set value to relates_to_choices
        relates_to_choices = ????????????? // Something like self.choices
        self.fields['duration'].choices = relates_to_choices

    duration = forms.ChoiceField(required=True)

现在,我有一个具有类

的views.py文件
class AddDurationView(FormView):
    template_name = 'physician/add_duration.html'
    form_class = AddDurationForm

1 个答案:

答案 0 :(得分:4)

覆盖视图上的get_form_kwargs()方法。

views.py

class AddDurationView(FormView):
    template_name = 'physician/add_duration.html'
    form_class = AddDurationForm

    def get_form_kwargs(self):
        kwargs = super(AddDurationView, self).get_form_kwargs()
        kwargs['duration_choices'] = (
            ('key1', 'display value 1'),
            ('key2', 'display value 2'),
        )
        return kwargs

forms.py

class AddDurationForm(forms.Form):
    duration = forms.ChoiceField(required=True)

    def __init__(self, duration_choices, *args, **kwargs): 
        super(AddDurationForm, self).__init__(*args, **kwargs)
        // set value to duration_choices
        self.fields['duration'].choices = duration_choices