I was working on SetPasswordForm
and I was wondering if there's a way to customize password hint showing below password form.
Your password can't be too similar to your other personal information.
Your password must contain at least 8 characters.
...
I was trying to override it and seeing source code but I couldn't figure out where it comes from.
views.py
class CustomPasswordResetConfirmView(PasswordResetConfirmView):
form_class = CustomSetPasswordForm
template_name = 'users/password_reset_confirm.html'
forms.py
class CustomSetPasswordForm(SetPasswordForm):
def __init__(self, *args, **kawrgs):
super(CustomSetPasswordForm, self).__init__(*args, **kwargs)
self.fields['new_password1'].label = "Custom Field Name"
...
These hints are coming from below method. password_validators_help_text_html()
method returns list of hints which are shown below password form.
django.contrib.auth.forms.py
class SetPasswordForm(forms.Form):
"""
A form that lets a user change set their password without entering the old
password
"""
...
new_password1 = forms.CharField(
label=_("New password"),
widget=forms.PasswordInput,
strip=False,
help_text=password_validation.password_validators_help_text_html(), # this help text contains list of hints
)
...
You can modify this method as below
from django.utils.html import format_html
from django.contrib.auth.password_validation import password_validators_help_texts
def _custom_password_validators_help_text_html(password_validators=None):
"""
Return an HTML string with all help texts of all configured validators
in an <ul>.
"""
help_texts = password_validators_help_texts(password_validators)
help_items = [format_html('<li>{}</li>', help_text) for help_text in help_texts]
#<------------- append your hint here in help_items ------------->
return '<ul>%s</ul>' % ''.join(help_items) if help_items else ''
custom_password_validators_help_text_html = custom_validators_help_text_html=lazy(_custom_password_validators_help_text_html, text_type)
Than add this to your CustomSetPasswordForm
class CustomSetPasswordForm(SetPasswordForm):
new_password1 = forms.CharField(
label=_("New password"),
widget=forms.PasswordInput,
strip=False,
help_text=custom_validators_help_text_html(),
) # added custom help text method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With