Maxsteel
Maxsteel

Reputation: 2040

Error on raising ValidationError as dictionary

Django newbie here. I am trying to raise an error for email field in my custom form. My forms.py has following code to validate email:

def clean_email(self):
    email = self.cleaned_data["email"]
        try:
            User._default_manager.get(email=email)
                except User.DoesNotExist:
                return email
        raise ValueError({'email':'Email already registered. 
                     Login to continue or use another email.'})

On entering existing email again, I get following error on my debug screen of app:

enter image description here

What am I doing wrong here? I am following this LINK

EDIT Getting this error on changing ValueError to ValidationError The argument field must be None when the error argument contains errors for multiple fields.

Upvotes: 5

Views: 6906

Answers (3)

Bobort
Bobort

Reputation: 3218

When using clean_<fieldname>, don't specify a dictionary. Any ValidationError that is raised in that method is automatically associated with that field.

def clean_email(self):
    email = self.cleaned_data["email"]
    try:
        User._default_manager.get(email=email)
    except User.DoesNotExist:
        return email
    raise ValidationError('Email already registered. 
                 Login to continue or use another email.')

Upvotes: 4

Eugene Soldatov
Eugene Soldatov

Reputation: 10135

Use raise ValidationError instead of raise ValueError:

def clean(self):
    email = self.cleaned_data["email"]
    try:
        User._default_manager.get(email=email)
    except User.DoesNotExist:
        return self.cleaned_data
    raise ValidationError({'email':'Email already registered. Login to continue or use another email.'})

Upvotes: 4

Daniel Roseman
Daniel Roseman

Reputation: 599600

You shouldn't be raising ValueError, you should be raising forms.ValidationError.

Upvotes: 3

Related Questions