Django Formset无法正常工作

时间:2017-02-20 21:15:20

标签: python django django-forms

我正在尝试使用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>

enter image description here

请帮忙。

2 个答案:

答案 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

编辑:

另请参阅this表单集验证和错误,以及this如何在模板中轻松使用它们。

答案 1 :(得分:0)

问题是

def formview(request):
     newformset = formset_factory(NewForm)
     if form.is_valid():
         formset = newformset(request.POST)
         ..
          ...
         ...

     else:
         formset = newformset()