[Fixed]-Django custom user authentication is not working properly

1👍

Try moving the password comparison logic present in the clean_password() function to a clean() function in the UserCreationForm.

The clean_fieldname() function should operate on the field fieldname and not any other field.

Also, when fields validation depends on each other then the best place to place the validation logic is inside the clean() method.

From Django docs:

We are performing validation on more than one field at a time, so the
form’s clean() method is a good spot to do this.

By the time the form’s clean() method is called, all the individual
field clean methods will have been run (the previous two sections), so
self.cleaned_data will be populated with any data that has survived so
far. So you also need to remember to allow for the fact that the
fields you are wanting to validate might not have survived the initial
individual field checks.

Code:

class UserCreationForm(forms.ModelForm):
    ...

    def clean(self):
        cleaned_data = super(UserCreationForm, self).clean()
        password1 = cleaned_data.get("password1")
        password2 = cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("passwords don't match")
        return cleaned_data 

0👍

The problem is, you doesn’t has a ‘password’ field,
you need change the method name to, clean_password1 or clean_password2.

the method you created clean_password, will never be called
because there is no field called password

def clean_password1(self):
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError("passwords don't match"")
    return password1

Leave a comment