开发者

Dynamically remove a choice option from a form

开发者 https://www.devze.com 2023-03-09 06:09 出处:网络
I have a form like this: RANGE_CHOICES = ( (\'last\', \'Last Year\'), (\'this\', \'This Year\'), (\'next\', \'Next Year\'),

I have a form like this:

RANGE_CHOICES = (
    ('last', 'Last Year'),
    ('this', 'This Year'),
    ('next', 'Next Year'),
)   

class MonthlyTotalsForm(forms.Form):
    range = forms.ChoiceField(choices=RANGE_CHOICES, initial='this')

It's displayed in the template like this:

{{ form.range }}
开发者_开发百科

In some situations I don't want to show the 'Next Year' option. Is it possible to remove this option in the view where the form is created?


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消