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
答案 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