簡體   English   中英

如何為 django 中的密碼表單覆蓋 help_text 和 label

[英]How to override help_text and label for password form in django

我的forms.py中有以下表格。 由於某種原因,覆蓋 label 和 help_text 的username名字段WORKS和(兩者)密碼字段都沒有。

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'password1', 'password2']
        labels = {
            'username': 'My Username Label',
            'password1': 'My Password1 Label',
            'password2': 'My Password2 Label',
        }
        help_texts = {
            'username': 'My username help_text',
            'password1': 'My password1 help_text',
        }

呈現默認 django 標簽/help_texts 時顯示密碼字段:

Your password can’t be too similar to your other personal information.
Your password must contain at least 8 characters.
...

我已經閱讀了這些答案,但它們沒有幫助: Q1 Q2 Q3

我也閱讀了文檔, 這里有一個注釋(綠色注釋降低頁面)似乎相關,但我不太明白。 它提到了以聲明方式定義的字段,我沒有這樣做。 也不會解釋為什么它適用於username而不是password1

覆蓋 class 形式的__init__(...)方法,

class CreateUserForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['password1'].label = 'password1 label' self.fields['password2'].label = 'password2 label' self.fields['password1'].help_text = 'password1 help_text' self.fields['password2'].help_text = 'password2 help_text'

我也有同樣的擔憂。 我嘗試了很多方法,但最好的方法是編寫自己的驗證器。 假設我們想更改錯誤文本“此密碼完全是數字”。 到別的東西行“پسوردشماکاملاعدداست。لطفاآنراتغییردهید。”。

假設我的應用在我的項目中是auth_app

在您的應用程序中創建一個validator.py

import re

from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _


class CustomNumericPasswordValidator:
    """
    Validate whether the password is alphanumeric.
    """
    def validate(self, password, user=None):
        if password.isdigit():
            raise ValidationError(
                _("پسورد شما کاملا عدد است. لطفا آن را تغییر دهید."),
                code='password_entirely_numeric',
            )

    def get_help_text(self):
        return _('Your password can’t be entirely numeric.')

然后 go 到settings.py並將您的驗證器替換為默認值

{
    'NAME': 'auth_app.validators.CustomNumericPasswordValidator',
},

保存並享受變化。

這是對我們定義為新錯誤消息的測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM