MiniGunnR
MiniGunnR

Reputation: 5800

Why is this Django form not raising ValidationError?

I'm trying to raise a ValidationError during registration if a use with the same email already exists. I have added the following method in my form to do that.

    def clean_email(self):
        email = self.cleaned_data.get('email')

        if email:
            try:
                user = User.objects.get(email=email)
            except:
                user = None
        if user is not None:
            raise forms.ValidationError('This email address is unavailable!')

        return email

However, I have included a print statement after except and the console always prints that value. So it is for some reason executing that part of the code even if the user with the specified email address exists.

What am I doing wrong?

Upvotes: 1

Views: 1024

Answers (1)

Prakhar Trivedi
Prakhar Trivedi

Reputation: 8526

The problem is in return fuction, in the place of try ,except just use exists() method for code simplification :

from django.contrib.auth.models import User

def clean_email(self):
    email = self.cleaned_data.get('email')

    if email:
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('This email address is unavailable!')
        else:
            pass

    return email

And make sure that html code is also updated like this in your form template :

   {% if form.errors %}
        {% for field in form %}
            {% for error in field.errors %}
                <div class="row">
                    {{ error|escape }}
                </div>
            {% endfor %}
        {% endfor %}
        {% for error in form.non_field_errors %}
            <div class="row">
                {{ error|escape }}
            </div>
        {% endfor %}
    {% endif %}

Upvotes: 5

Related Questions