Skip to main content

SetPasswordMixin

Form mixin that validates and sets a password for a user.

Attributes

AttributeTypeDescription
error_messagesdict = {"password_mismatch": "The two password fields didn’t match."}A dictionary mapping error codes to localized error messages used during password validation, specifically for reporting password mismatches.

Methods


create_password_fields()

@classmethod
def create_password_fields(
label1: string = Password,
label2: string = Password confirmation
) - > tuple

Generates a pair of Django form fields for password entry and confirmation with standard security attributes.

Parameters

NameTypeDescription
label1string = PasswordThe display label for the primary password input field.
label2string = Password confirmationThe display label for the secondary password verification field.

Returns

TypeDescription
tupleA tuple containing two CharField instances configured with PasswordInput widgets.

validate_passwords()

@classmethod
def validate_passwords(
password1_field_name: string = password1,
password2_field_name: string = password2
) - > null

Compares two password fields in the form's cleaned data to ensure they are identical.

Parameters

NameTypeDescription
password1_field_namestring = password1The key in cleaned_data representing the primary password field.
password2_field_namestring = password2The key in cleaned_data representing the confirmation password field.

Returns

TypeDescription
nullnull

validate_password_for_user()

@classmethod
def validate_password_for_user(
user: [User](../models/user.md?sid=django_contrib_auth_models_user),
password_field_name: string = password2
) - > null

Runs Django's password validation suite against a specific user instance to enforce complexity and security rules.

Parameters

NameTypeDescription
user[User](../models/user.md?sid=django_contrib_auth_models_user)The user model instance against which the password complexity is validated.
password_field_namestring = password2The key in cleaned_data containing the password string to be validated.

Returns

TypeDescription
nullnull

set_password_and_save()

@classmethod
def set_password_and_save(
user: [User](../models/user.md?sid=django_contrib_auth_models_user),
password_field_name: string = password1,
commit: boolean = True
) - > [User](../models/user.md?sid=django_contrib_auth_models_user)

Updates the user's password with the hashed value from the form and optionally persists the user to the database.

Parameters

NameTypeDescription
user[User](../models/user.md?sid=django_contrib_auth_models_user)The user model instance whose password will be updated.
password_field_namestring = password1The key in cleaned_data containing the plain-text password to hash.
commitboolean = TrueDetermines whether to call the save() method on the user instance after setting the password.

Returns

TypeDescription
[User](../models/user.md?sid=django_contrib_auth_models_user)The updated user model instance.