我正在尝试使用django表单中提供的formsets。 这是forms.py
from django import forms
class NewForm(forms.Form):
username = forms.CharField(max_length=100, label="Username")
email = forms.EmailField(label="email")
city = forms.CharField(label="city")
Views.py
from django.shortcuts import render
# Create your views here.
from .forms import NewForm
from django.forms import formset_factory
def formview(request):
if request.method == 'POST':
form = NewForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
city = form.cleaned_data['city']
email = form.cleaned_data['email']
print(type(form.cleaned_data))
NewFormSet = formset_factory(NewForm)
formset = NewFormSet()
for form in formset:
print(form)
for k,v in form.cleaned_data.items():
print(k,v)
else:
print("ddd")
form = NewForm()
formset = 0
return render(request, 'form.html', {'form':form,'formset':formset})
早些时候它工作得很好
但问题是,当我添加此formset代码时,它显示错误
模板:
<html>
<head>
<title>The Form</title>
</head>
<body>
<form method='POST'>{% csrf_token %}
{% for field in form %}
{{ field.error }}
<br />
{{ field.label }}
{{ field }}
<br />
{% endfor %}
<input type="Submit" value="Submit">
</form>
{% for f in formset %}
<form method='POST'>{% csrf_token %}
{% for field in f %}
{{ f.error }}<br />
{{ f.label }}
{{ f }}
<br />
{% endfor %}
</form>
{% endfor %}
</body>
</html>
请帮忙。
答案 0 :(得分:0)
你需要调用form.is_valid()
来清除/验证它,之前它没有cleaned_data
,你还应该考虑重命名循环变量,因为你已经有一个名为form
的变量:
for newform in formset:
if newform.is_valid():
for k,v in newform.cleaned_data.items():
print(k,v)
您还可以在formset上调用is_valid()
来验证formset中的所有表单:
if formset.is_valid():
for newform in formset:
for k,v in newform.cleaned_data.items():
print(k,v)
但请注意,此时newform
没有数据,只是空NewForm
。
编辑:
答案 1 :(得分:0)
问题是
def formview(request):
newformset = formset_factory(NewForm)
if form.is_valid():
formset = newformset(request.POST)
..
...
...
else:
formset = newformset()