Reputation: 2084
I am trying to create a custom validator for my form by overwriting the clean() method, and for some reason validation errors are not being raised properly. Here's my code:
forms.py
from django import forms
from django.contrib.auth import get_user_model
class EmailForm(forms.Form):
email_field = forms.EmailField(label='E-mail address', max_length=128)
def clean(self):
cleaned_data = super(EmailForm, self).clean()
email = cleaned_data.get('email')
try:
u = get_user_model().objects.get(email=email)
raise forms.ValidationError("E-mail already in database.")
print('validation error raised')
except:
pass
views.py
from django.shortcuts import render
from django.contrib import messages
from .forms import EmailForm
def email_form(request):
if request.method == 'POST':
form = EmailForm(request.POST)
# If the form is valid...
if form.is_valid():
messages.add_message(request, messages.SUCCESS, "Kaboom! Your referral e-mail was sent. Hang tight - we'll be sure to let you know when your friend makes a purchase.")
else:
messages.add_message(request, messages.ERROR, 'Error!')
else:
form = EmailForm()
return render(request, 'template.html', {'form': form})
template.html
<form action="{% url 'form-process' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
When I submit this form with input that should raise a validation error (i.e., an e-mail address that is already associated with a user in my database), I get the 'success' message rather than an error. The strangest part about it is that 'validation error raised' is printed in my console — but for some reason the form processes and form.is_valid() passes as True.
Can anyone tell me why form.is_valid doesn't output an error in the code below when a duplicate e-mail is entered?
Upvotes: 0
Views: 4071
Reputation: 5649
It can't raise exception, because you catch is in except.
def clean(self):
cleaned_data = super(EmailForm, self).clean()
email = cleaned_data.get('email')
users = get_user_model().objects.filter(email=email)
if users.exists():
raise forms.ValidationError("E-mail already in database.")
Upvotes: 3