使用formset,Django上的此字段是必需的错误

时间:2015-12-07 14:44:28

标签: django django-forms

我有三种形式,forms.py:

class HotelForm(forms.Form):
        rooms = forms.IntegerField(label=(u'Rooms'), min_value=1)

class TouristsForm(forms.Form):
        adult = forms.IntegerField(label=(u'Adults'), min_value=1, initial=1)
        children = forms.IntegerField(label=(u'Children'), min_value=0, initial=0, required=False)

class ChildrenAgeForm(forms.Form):
        children_age = forms.IntegerField(label=(u'Children Age'), min_value=2, max_value=10, initial=2, required=False)

我是如何在views.py中实现formset和验证的:

def bookingForm(request):
        TouristsFormSet = formset_factory(TouristsForm, extra = 1, max_num = 15)
        ChildrenAgeFormSet = formset_factory(ChildrenAgeForm, extra = 1, max_num = 20)
        if request.method == 'POST':
                booking_form = HotelForm(request.POST, prefix='booking_form')
                tourists_formset = TouristsFormSet(request.POST, prefix='tourists')
                childrenage_formset = ChildrenAgeFormSet(request.POST, prefix='childrenage')
                if booking_form.is_valid() and tourists_formset.is_valid() and childrenage_formset.is_valid():
                        rooms = booking_form.cleaned_data['rooms']

                        for i in range(0, tourists_formset.total_form_count()):
                                tourists_form = tourists_formset.forms[i]
                                tourists = tourists_form.cleaned_data

                        for n in range(0, childrenage_formset.total_form_count()):
                                childrenage_form = childrenage_formset.forms[n]
                                childrenage = childrenage_form.cleaned_data

                        template = get_template("booking/result.html")
                        context = Context({'tourists_formset':tourists_formset, 'childrenage_formset':childrenage_formset })
                        html = template.render(context)
                        return HttpResponse( html ) 

        else:
                booking_form = HotelForm()
                tourists_formset = TouristsFormSet(prefix='tourists')
                childrenage_formset = ChildrenAgeFormSet(prefix='childrenage')
        return render(request, 'booking/booking.html', { 'booking_form' : booking_form, 'tourists_formset' : tourists_formset, 'childrenage_formset' : childrenage_formset })

这就是我实现html文件的方式:

{{ tourists_formset.management_form }}
{% for tourists in tourists_formset %}
   {{ tourists }}
{% endfor %}
{{ childrenage_formset.management_form }}
{% for childrenage in childrenage_formset %}
   {{ childrenage }}
{% endfor %}

每当我填写表单中的所有字段时,我都会收到错误消息'此字段是必填字段'为HotelForm形式。我不明白为什么会这样。谢谢你的帮助

1 个答案:

答案 0 :(得分:2)

处理POST请求时使用前缀。

booking_form = HotelForm(request.POST, prefix='booking_form')

您需要为GET请求使用相同的前缀。

booking_form = HotelForm(prefix='booking_form')