我有这样的形式:

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

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

最佳答案

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)

关于django - 从表单中动态删除选择选项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6188991/

10-12 21:50