在我的Django应用程序中,我有三种形式:
class RoomsForm(forms.Form):
rooms = forms.IntegerField(min_value=1)
class TouristsForm(forms.Form):
adult = forms.IntegerField(label=(u'Adults'), min_value=1, initial=1, widget = forms.HiddenInput)
children = forms.IntegerField(label=(u'Children'), min_value=1, required=False, widget = forms.HiddenInput)
class ChildrenAgeForm(forms.Form):
children_age = forms.IntegerField(min_value=2, max_value=10, required=False, widget = forms.HiddenInput)
在view.py中我尝试清理数据:
def RoomsForm(request):
TouristsFormSet = formset_factory(TouristsForm)
ChildrenAgeFormSet = formset_factory(ChildrenAgeForm)
if request.method == 'POST':
rooms_form = RoomsForm(request.POST, prefix='rooms_form')
tourists_formset = TouristsFormSet(request.POST, prefix='tourists')
childrenage_formset = ChildrenAgeFormSet(request.POST, prefix='childrenage')
if rooms_form.is_valid() and tourists_formset.is_valid() or childrenage_formset.is_valid():
rooms = rooms_form.cleaned_data['rooms']
for i in range(0, tourists_formset.total_form_count()):
tourists_form = tourists_formset.forms[i]
print tourists_form.cleaned_data
但它总是在/ rooms /' rooms'上升错误KeyError。 有人可以帮我吗?
答案 0 :(得分:3)
在这一行中,您使用的是or
而不是and
,因此无法保证rooms_form
无效。
if rooms_form.is_valid() and tourists_formset.is_valid() or childrenage_formset.is_valid():
当rooms_form
无效时,room
不在rooms_form.cleaned_data
,因此您获得了KeyError
。