password_confirmation in forms.py

Can I add password_confirmation in fields ? I am getting error.

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

class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = User        
        fields = ('first_name','last_name','email','date_of_birth', 'gender', 'user_type', 'phone', 'address','photo', 'password', 'password_confirmation' )

In all cases, when you encounter an error, you need to post the complete error with the traceback from the console.

What does your User model look like? (Is password_confirmation one of the fields in the model?) What about the view that is using this form?

1 Like

Thanks @KenWhitesell . My forms.py is like below.

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

class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = User        
        fields = ('first_name','last_name','email','date_of_birth', 'gender', 'user_type', 'phone', 'address','photo', 'password' )
        error_messages = {
            field: {
                'required': f"{field.replace('_', ' ').title()} is required."
            }
            for field in fields
        }

No, password_confirmation is not one of the fields in the model.

My view is like below.

class UserRegisterView( FormView ):
    template_name = 'register.html'
    form_class = CustomUserCreationForm
    
    redirect_authenticated_user = True
    success_url = reverse_lazy('dashboard')      

    def form_valid( self, form ):
        user = form.save()
        if user is not None:
            login( self.request, user )
        return super( UserRegisterView, self ).form_valid( form )
    
    def get( self, *args, **kwargs ):
        if self.request.user.is_authenticated:
            return redirect('dashboard')
        return super( UserRegisterView, self ).get( *args, **kwargs )
    
    def form_invalid(self, form):
        for field in form:
            for error in field.errors:
                if error == "This field is required.":
                    messages.error(self.request, f"{field.label} is required")
                else:
                    messages.error(self.request, f"{field.label}: {error}")
        return super(UserRegisterView, self).form_invalid(form)

I am getting form validation message This field is required.for password confirmation field. But I would like to get form validation message Password Confirmation is required. for password confirmation field.

Then it doesn’t belong in the Meta.fields list. It needs to be defined as a normal form field in the CustomUserCreationForm.

You would do this in your clean_password_confirmation method in your form.

Side note: The UserCreationForm already defines a password1 and password2 field. Is the intent of adding a password_confirmation field to add a third field for this purpose?

1 Like

Thanks @KenWhitesell .

Could you please show me some sample code in this regard ?

No, I wouldn’t like to add third field. Actually I would like to show Password Confirmation is required as Validation Message for password2.

Currently I am showing validation message Password is required. for password1.

Your best example for that would be to look at the existing django.contrib.auth.forms.BaseUserCreationForm that you are inheriting from.

1 Like

Thanks @KenWhitesell . Now I am using below code.

# forms.py
from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import ValidationError
from .models import User

class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = User        
        fields = ('first_name','last_name','email','date_of_birth', 'gender', 'user_type', 'phone', 'address','photo', 'password1', 'password2' )
        error_messages = {
            field: {
                'required': f"{field.replace('_', ' ').title()} is required."
            }
            for field in fields
        }
        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name in self.fields:
            self.fields[field_name].error_messages.update(self.Meta.error_messages[field_name])
    
    def clean_password1(self):
        password1 = self.cleaned_data.get('password1')
        if not password1:
            raise ValidationError("Password is required.")
        return password1

and

<label class="form-label">PassWord</label>
<input type="password" class="form-control" name="password1" />                          
{% if form.password1.errors %}
    <div class="alert alert-danger">{{ form.password1.errors }}</div>
{% endif %}

I am getting errror message Password1 is required.. But I would like to get Password is required.

Thanks

So change how you’re defining the error_messages dict in the CustomUserCreationForm.Meta class to create the desired message for that field.