从表单中动态删除选项选项

时间:2011-05-31 14:21:03

标签: django

我有一个这样的表格:

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 }}

在某些情况下,我不想显示“下一年”选项。是否可以在创建表单的视图中删除此选项?

1 个答案:

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