当表单字段未正确验证时,我想在表单上方显示所有错误消息。例如,当我在first_name和last_name字段中输入数字并提交表单时,错误(2)将出现在 li 标记中的表单上方。目前,所有表单验证器都在forms.py中声明。
我应该在模板/视图中进行哪些更改,以在 li 标记中显示字段名称而不显示ValidationError内容?
views.py
if request.method == 'POST':
person_form = PersonForm(request.POST)
phone_form = PhoneForm(request.POST)
email_form = EmailForm(request.POST)
if person_form.is_valid() and phone_form.is_valid() and email_form.is_valid():
person = person_form.save()
phone = phone_form.save(False)
email = email_form.save(False)
phone.person = person
email.person = person
phone.save()
email.save()
messages.success(request, f"Dodano nowy kontakt: {request.POST['first_name']} {request.POST['last_name']}")
return HttpResponseRedirect('/')
else: # GET
person_form = PersonForm()
phone_form = PhoneForm()
email_form = EmailForm()
return render(request,
'address_book/add_contact.html',
{
'person_form':person_form,
'phone_form':phone_form,
'email_form':email_form,
})
forms.py
def validate_first_name(str):
if any(char.isdigit() for char in str):
raise forms.ValidationError('Pole Imię musi zawierać tylko litery')
def validate_last_name(str):
if any(char.isdigit() for char in str):
raise forms.ValidationError('Pole Nazwisko musi zawierać tylko litery')
class PersonForm(forms.ModelForm):
first_name = forms.CharField(label='Imię', validators=[validate_first_name, ])
last_name = forms.CharField(label='Nazwisko', validators=[validate_last_name, ])
class Meta:
model = Person
fields = '__all__'
* add_contact.html(模板)*
<div class="row">
<div class="addEntryBox">
{% if person_form.errors or phone_form.errors or email_form.errors %}
{% for error in person_form.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
{% for error in phone_form.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
{% for error in email_form.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
{% endif %}
<form action="{% url 'address_book:contact_add' %}" method="post">
{% csrf_token %}
{{ person_form.as_p }}
{{ phone_form.as_p }}
{{ email_form.as_p }}
<div><button id="saveContactButton" type="submit" class="waves-effect waves-light btn"><i class="small material-icons left">save</i>Zapisz</button></div>
</form>
</div>
</div>