我正在开发SetPasswordForm
,我想知道是否有一种方法可以自定义显示在密码表单下方的密码提示。
Your password can't be too similar to your other personal information.
Your password must contain at least 8 characters.
...
我试图覆盖它并查看源代码,但我无法弄清楚它来自哪里。
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"
...
最佳答案
这些提示来自以下方法。 password_validators_help_text_html()
方法返回提示列表,显示在密码表单下方。
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
)
...
您可以如下修改此方法
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)
然后将其添加到您的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
关于Django:如何自定义密码提示列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54976822/