2015-12-07 43 views
0

所需錯誤的Django的我有三種形式,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) 

這就是我如何實現FORMSET和views.py驗證:

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

當我填寫表格,我有「此字段是必需」爲HotelFor錯誤的所有字段每次m形式。我不明白爲什麼會發生。感謝您的幫助

+0

你在is_valid塊內的循環根本沒有意義。你最終只能得到最後一種形式的值。 –

回答

2

您在處理POST請求時使用了前綴。

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

您需要爲GET請求使用相同的前綴。

booking_form = HotelForm(prefix='booking_form')