我有一个这样的表格:
RANGE_CHOICES = (
('last', 'Last Year'),
('this', 'This Year'),
('next', 'Next Year'),
)
class MonthlyTotalsForm(forms.Form):
range = forms.ChoiceField(choices=RANGE_CHOICES, initial='this')
它在模板中显示如下:
{{ form.range }}
在某些情况下,我不想显示“下一年”选项。是否可以在创建表单的视图中删除此选项?
答案 0 :(得分:11)
class MonthlyTotalsForm(forms.Form):
range = forms.ChoiceField(choices=RANGE_CHOICES, initial='this')
def __init__(self, *args, **kwargs):
no_next_year = kwargs.pop('no_next_year', False)
super(MonthlyTotalsForm, self).__init__(*args, **kwargs)
if no_next_year:
self.fields['range'].choices = RANGE_CHOICES[:-1]
#views.py
MonthlyTotalsForm(request.POST, no_next_year=True)