Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove password confirmation field in django UserCreationForm

I have created a UserCreationForm as follow:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1']

        exclude = ['password2']

    def __init__(self, *args, **kwargs):
        super(UserRegisterForm, self).__init__(*args, **kwargs)
        # for fieldname in ['password2']:
        self.fields['password2'].help_text = None
        self.fields['password1'].help_text = None
        self.fields['username'].help_text = None

However I am trying to remove Password Confirmation field from the register form, but so far couldn't find any solution for that. Do you know how to resolve this problem?

like image 839
J2015 Avatar asked Sep 05 '25 03:09

J2015


1 Answers

You can delete password2 in __init__ method:


class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1']


    def __init__(self, *args, **kwargs):
        super(UserRegisterForm, self).__init__(*args, **kwargs)
        del self.fields['password2']
        self.fields['password1'].help_text = None
        self.fields['username'].help_text = None

Password confirmation is verified by the clean_password2() method.

 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(
            self.error_messages['password_mismatch'],
            code='password_mismatch',
        )
    return password2 

Update


So as @AbdulAzizBarkat pointed out password2 also used in _post_clean() method.

If you use password2 in your form and don't use password confirmation. Chances are that password2 and password1 don't match, and you will not pass validation. Because password2 must be also pass validation in _post_clean method.

So use:

del self.fields['password2']
like image 183
NKSM Avatar answered Sep 07 '25 17:09

NKSM