我正在尝试使用具有相同“name”属性的多个字段来验证表单。
第一位用户的表格:
class BuyTicketFormEmail(forms.Form):
email = forms.EmailField()
first_name_customer = forms.CharField(max_length=191)
last_name_customer = forms.CharField(max_length=191)
其他用户的表单
class UserForm(forms.Form):
first_name_user = forms.CharField(max_length=191)
last_name_user = forms.CharField(max_length=191)
表单:https://i.imgur.com/mTdaZvK.jpg 客户可以添加多个其他用户,我不知道确切的号码,都具有相同的名称。
在HTML中我只显示一个表单,我该如何验证?
答案 0 :(得分:0)
我不在家,我是用智能手机写的,对不起,如果代码不是100%正确的话。但是你会得到大线。
对于视图:
def add_user(request):
i = 1
n = 5 #change it to the number of users you want
all_users_forms = []
while i < n+1 :
one_user_form = UserForm()
all_users_forms += one_user_form
i += 1
context = {'all_users_forms':all_users_forms}
template = 'form.html' #change it to your template name
return render(request, template, context)
在模板中渲染你的表单
{% for form in all_users_forms %}
{{ form }}
答案 1 :(得分:0)
我不知道确切的长度(N),但你的回答帮助我找到解决方案,谢谢
names = request.POST.getlist('first_name')
surnames = request.POST.getlist('last_name')
id = 0
for name in names:
data = {
'first_name': name,
'last_name': surnames[id]
}
users_form = self.users_form_class(data)
id += 1
if users_form.is_valid():
f_name = users_form.cleaned_data['first_name']
l_name = users_form.cleaned_data['last_name']
else:
return HttpResponse('String is too long, or containts incorrect characters')