Rahul S Dev
Rahul S Dev

Reputation: 61

How to do Password and Confirm password validation in Django Forms

It's a signup form. When I input different passwords it doesn't show any error. I referred many sites, please help me

    from django import forms
    from .models import *
    class signup_form(forms.Form):
          firstname = forms.CharField()
          lastname = forms.CharField()
          email = forms.EmailField()
          GENDER_CHOICES = (
            ('M', 'Male'),
            ('F', 'Female'),
        )
          Qual_choices = (
    ('UG', 'UG'),
    ('PG', 'PG')
    )
          gender = forms.ChoiceField( widget=forms.RadioSelect,choices=GENDER_CHOICES)
          qualification =           forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=Qual_choices)
          Password = forms.CharField(widget=forms.PasswordInput())
          ConfirmPassword = forms.CharField(widget=forms.PasswordInput())

          def clean(self):

               cleaned_data = super(signup_form, self).clean()
               password = cleaned_data.get('Password')
               confirm_password = cleaned_data.get('ConfirmPassword')
               if password and confirm_password:
                     if password != confirm_password:
                     raise forms.ValidationError('Password mismatch')

               return confirm_password

Upvotes: 1

Views: 4305

Answers (1)

ngawang13
ngawang13

Reputation: 673

you need to add self before clean_data

 def clean_password2(self):

    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError("Passwords do not match")
    return password2

if the form is validated than do this

  if register_form.is_valid():
            user = register_form.save(commit=False)
            user = register_form.save()
            username = form.cleaned_data.get('username')
            raw_password = register_form.cleaned_data.get('password1')
            user = authenticate(request, username=username, 
            password=raw_password)
            login(request, user)
            return redirect('some url')

Upvotes: 1

Related Questions