我知道这个问题引发了很多,我已经阅读了与该问题有关的所有其他答案,但我仍然无法弄清楚如何使其发挥作用。我甚至在一个非常简单的表格上跟着那个tuto(https://godjango.com/9-forms-part-4-formsets/),但我仍然得到了这个着名的错误:
['ManagementForm data is missing or has been tampered with']
models.py:
class InviteForm2(forms.Form):
"""
Form for member email invite
"""
Email = forms.EmailField(
widget=forms.EmailInput(attrs={
'placeholder': "Member's mail",
}),
required=False)
class BaseLinkFormSet(BaseFormSet):
def clean(self):
"""
Adds validation to check that no two links have the same anchor or URL
and that all links have both an anchor and URL.
"""
if any(self.errors):
return
Email = []
duplicates = False
for form in self.forms:
if form.cleaned_data:
email = form.cleaned_data['Email']
# Check that no two links have the same anchor or URL
if email:
if email in emails:
duplicates = True
emails.append(email)
if duplicates:
raise forms.ValidationError(
'You cannot provide twice the same mail',
code='duplicate_links'
)
views.py:
def printmail2(request):
InviteFormSet = formset_factory(InviteForm2, formset=BaseLinkFormSet, extra=7)
if request.method == 'POST':
formset = InviteFormSet(request.POST, prefix='pfix')
if(formset.is_valid()):
for i in formset:
a = i.value()
print(a)
print("success")
else:
print("form not valid")
else:
formset = InviteForm2()
return render(request,'invite2.html',
{'formset':formset})
invite2.html:
{% load staticfiles %}
<h2>Form</h2>
<form method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<div class="link-formset">
<p>
{{ form.label_tag }}{{ form }}
</div>
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<input type="submit" value="Send Invitations" class="button"/>
</form>
<!-- Include formset plugin - including jQuery dependency -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'js/jquery.formset.js' %}"></script>
<script>
$('.link-formset').formset({
addText: 'add link',
deleteText: 'remove'
});
</script>
你能帮我解决一下吗? 谢谢你;)
答案 0 :(得分:3)
对于您正在进行的帖子请求,
formset = InviteFormSet(request.POST, prefix='pfix')
但是对于获取请求,您缺少前缀,而是使用表单类。
formset = InviteForm2()
您需要使get请求的formset与post请求的formset一致:
formset = InviteFormSet(prefix='pfix')