Django的月份列表

时间:2010-09-09 00:28:48

标签: python django

我正在尝试使用带有月份列表的精选表单,但我似乎无法正确发布。

形式:

   class MonthForm(forms.Form):
        months = [('January','January'),
                  ('February','February'),
                  ('March','March'),
                  ('April','April'),
                  ('May','May'),
                  ('June','June'),
                  ('July','July'),
                  ('August','August'),
                  ('September','September'),
                  ('October','October'),
                  ('November','November'),
                  ('December','December'),]
        month = forms.ChoiceField(months)

视图:

def table_view(request):
    if request.method == 'POST':
        month = MonthForm(request.POST).cleaned_data['month']
        print month

我一直收到这个错误:

'MonthForm' object has no attribute 'cleaned_data'

1 个答案:

答案 0 :(得分:6)

cleaned_data属性仅在使用is_valid()验证表单后才会显示。

只需将代码更改为

即可
def table_view(request):
    if request.method == 'POST':
        form = MonthForm(request.POST)
        if form.is_valid():
            print form.cleaned_data['month']

在内部,如果检测到任何错误,{@ 1}}属性将被删除(请参阅第270行周围的cleaned_data),因此无法访问:

forms/forms.py

另请参阅:http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#processing-the-data-from-a-form