我知道这个问题已经提出了很多,我已经阅读了与该问题有关的所有其他答案,但我仍然不知道如何使其起作用。我什至在一个非常简单的表格上遵循了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>
您能帮我弄清楚吗?thx you;)
对于您正在执行的发布请求,
formset = InviteFormSet(request.POST, prefix='pfix')
但是,对于获取请求,您缺少前缀,而是使用表单类。
formset = InviteForm2()
您需要制作符合邮政请求的请求的表单集:
formset = InviteFormSet(prefix='pfix')