In my Django application, I have a contact us template with fields: company name, contact number, email address.
I have defined a def clean() to validate the email address and phone number as follows:
class ContactForm(forms.Form):
def clean(self):
super(ContactForm, self).clean()
email_address = self.cleaned_data.get('email_address')
contact_no = self.cleaned_data.get('contact_no')
if validate_email(email_address):
pattern = re.compile('^[2-9]\\d{9}$')
if bool(pattern.match(contact_no)):
return self.cleaned_data
else: # error not displayed
raise forms.ValidationError(
"Please enter a valid phone number")
else: # error not displayed
raise forms.ValidationError(
"Please enter a valid email address")
return self.cleaned_data
In the 'contact_us' template, I am correctly rendering the errors as well:
<form method="post" action="{% url 'contact' %}">
{% csrf_token %}
{{contact_form.as_p}
<input type="submit" value="Submit">
</form>
{% if contact_form.errors %}
{% for field in contact_form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
In views.py, even if the form is valid and an email is sent successfully, the form is not rendering again(as a fresh new form) on the template.
def contact(request):
contact_form = ContactForm()
if request.method == 'POST':
contact_form = ContactForm(request.POST)
if contact_form.is_valid():
company_name = contact_form.cleaned_data.get('company_name')
contact_no = contact_form.cleaned_data.get('contact_no')
email_address = contact_form.cleaned_data.get('email_address')
# send mail code
contact_form.save()
contact_form = ContactForm()
return render(request, './mysite/contact_us.html', {
'contact_form': contact_form, 'successful_submit': True})
return render(request, './mysite/contact_us.html', {
'contact_form': contact_form,
})
validate_email_address
– Avinash Raj'^[2-9]\\d{9}$
there should be one `\` in middle. – Shakil