2011-05-31 42 views
5

我有一个这样的形式:动态地从一个表格中删除一个选择的选项

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

在某些情况下,我不希望显示'下一年'选项。是否可以在创建窗体的视图中删除此选项?

回答

8
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

我没有编辑权限,但在方法定义之后缺少冒号。感谢您的回答! – mikemaccana 2011-08-01 16:08:54

+0

@nailer谢谢! – DrTyrsa 2011-08-02 09:34:53

相关问题