从表单中动态删除选项选项 [英] Dynamically remove a choice option from a form

查看:87
本文介绍了从表单中动态删除选项选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的表格:

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

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

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)

这篇关于从表单中动态删除选项选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆