New forms signup validation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class UserField(forms.CharField):
    def clean(self, value):
        super(UserField, self).clean(value)
        try:
            User.objects.get(username=value)
            raise forms.ValidationError("Someone is already using this username. Please pick an other.")
        except User.DoesNotExist:
            return value

class SignupForm(forms.Form):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    username = UserField(max_length=30)
    password = forms.CharField(widget=forms.PasswordInput())
    password2 = forms.CharField(widget=forms.PasswordInput(), label="Repeat your password")
    email = forms.EmailField()
    email2 = forms.EmailField(label="Repeat your email")
    
    def clean_email(self):
        if self.data['email'] != self.data['email2']:
            raise forms.ValidationError('Emails are not the same')
        return self.data['email']

    def clean_password(self):
        if self.data['password'] != self.data['password2']:
            raise forms.ValidationError('Passwords are not the same')
        return self.data['password']
    
    def clean(self,*args, **kwargs):
        self.clean_email()
        self.clean_password()
        return super(SignupForm, self).clean(*args, **kwargs)

More like this

  1. use oldforms validators in newforms forms by garywilson 6 years, 1 month ago
  2. Allow separation of GET and POST implementations by agore 11 months, 1 week ago
  3. LoginAsForm - Login as any User without a password by johnboxall 3 years, 11 months ago
  4. newforms: Add field-specific error in form.clean() by miracle2k 5 years, 10 months ago
  5. DRYer instantiation of Forms by SmileyChris 4 years, 1 month ago

Comments

rogelio (on May 5, 2008):

Thank you very much for the contribution, i'm using this snippet as a base form my signup form now =)

#

kiuz (on June 18, 2010):

Thanks, Is good to revolve this problem

http://stackoverflow.com/questions/851628/django-user-doesnotexist-does-not-exist

#

artur_mwaigaryan (on January 18, 2012):

very elegant solution :-)

#

(Forgotten your password?)