Django:如何自定义密码提示列表

时间:2019-03-04 04:53:26

标签: django django-forms

我正在研究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"
        ...

2 个答案:

答案 0 :(得分:1)

这些提示来自以下方法。 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

答案 1 :(得分:0)

您需要覆盖password_validators_help_texts

  

返回所有验证程序的帮助文本列表。这些向用户说明了密码要求。

还有另一种方法password_validators_help_text_html