I'm creating a contact form (therefore not using a model-based form) and I've come across the following problem, after adding a regex validator to my email field: the custom error message I've added is now being displayed twice. This happens when I enter an email such as 'something' (it doesn't match my regex nor has the default '@' symbol - if I add the '@' symbol, only one message shows up).
I'm not sure, but I'm guessing django's default validation + my custom validation are responsible for that, so I'm wondering (if that's the problem), what I can do to prevent the same message from showing up twice.
Thank you in advance!
forms.py:
from django import forms
from django.core.validators import RegexValidator
class ContactForm(forms.Form):
full_name = forms.CharField(required=True)
email = forms.EmailField(validators=[RegexValidator(regex=r'^\d+@([a-zA-Z0-9@-_]+)(\.[a-zA-Z0-9@-_]+)+\b')]
, error_messages={'invalid': 'This is my email error msg.'})
message = forms.CharField(widget=forms.Textarea)
That 'This is my email error msg' is the one showing up repeatedly » eg: * This is my email error msg * This is my email error msg
views.py:
def contact(request):
form = ContactForm(request.POST or None)
context = {"form":form}
if form.is_valid():
form_name = form.cleaned_data.get("full_name")
form_email = form.cleaned_data.get("email")
form_message = form.cleaned_data.get("message")
subject = "Message from %s (%s)" % (form_name, form_email)
from_email = form_email
to_email = ['myemail',]
contact_message = form_message
send_mail(subject, contact_message, from_email, to_email, fail_silently=False)
context = {"form":form,"thanks_msg": "Thank you!"}
return render(request, 'contact.html', context)
template:
<form action="" method="POST" class="form"> {% csrf_token %}
{% for field in form %}
<div class="fields-container">
<label class="label">{{ field.label }}</label>
{{ field }}
</div>
<p class="server-form-errors"> {{ field.errors.as_text }} </p>
{% endfor %}
<button type="submit" id="form-button">Submit</button>
</form>