我知道这个问题已经被提出了很多次,我已经阅读了所有其他与这个问题有关的答案,但我仍然不知道如何使它起作用。我甚至跟着那首芭蕾舞曲(
https://godjango.com/9-forms-part-4-formsets/
)在一个非常简单的形式上,但我仍然得到了这个著名的错误:
['ManagementForm data is missing or has been tampered with']
模型。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'
)
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>