ritratt
ritratt

Reputation: 1858

How to display an error message during registration for duplicate user?

I know it's simple and I have tried searching extensively but nothing works :(

When i try this in my forms.py:

class RegistrationForm(forms.Form):
    email = forms.EmailField(unique = True, error_messages = {'unique':'Duplicate Error!')
    password = forms.CharField( widget = forms.PasswordInput(render_value = False), label = "Password")

I get an error saying: init() got an unexpected keyword argument: unique

I see people getting it to work easily but clearly I am missing something. how can I add a custom error message for user registration using the form and view code given above? I want to display the error message beside the username field just like the error message displayes when the field is left empty.

thank you.

Upvotes: 0

Views: 1370

Answers (1)

Ariel Ponce
Ariel Ponce

Reputation: 46

Use the clean method on the form to validate this:

from django.contrib.auth.models import User

class RegistrationForm(forms.Form):
    email = forms.EmailField()
    password = forms.CharField( widget = forms.PasswordInput(render_value = False),label = "Password")

    def clean(self):

        if User.objects.filter(email=self.cleaned_data['email']).exists():
            msg = _(u'Duplicate Error!')
            self._errors['email'] = ErrorList([msg])
            del self.cleaned_data['email']
        return self.cleaned_data

Upvotes: 2

Related Questions