gpt4 book ai didi

django - 使用 formset 在 Django 上此字段是必填错误

转载 作者:行者123 更新时间:2023-12-05 05:24:41 26 4
gpt4 key购买 nike

我有三种形式,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 中实现表单集和验证的方式:

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 表格都会出现“此字段为必填项”错误。我不明白为什么会这样。感谢帮助

最佳答案

您在处理 POST 请求时使用了前缀。

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

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

booking_form = HotelForm(prefix='booking_form')

关于django - 使用 formset 在 Django 上此字段是必填错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34136260/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com