【发布时间】:2018-01-28 22:11:31
【问题描述】:
我使用 UserCreationForm 创建新用户。
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'is_active']
UserCreationForm 自动添加两个字段(Password1 和 Password2)。
如果密码太短,那么它会引发一个错误,告诉你。或者如果它太简单或太常见。它是通过django.contrib.auth.password_validation 完成的。
我想知道是否可以覆盖这些错误的消息。
现在密码验证的源代码是:
def validate(self, password, user=None):
if len(password) < self.min_length:
raise ValidationError(
ungettext(
"This password is too short. It must contain at least %(min_length)d character.",
"This password is too short. It must contain at least %(min_length)d characters.",
self.min_length
),
code='password_too_short',
params={'min_length': self.min_length},
)
但是当我尝试在表单定义中使用此代码来覆盖此错误消息时,标签会更改,但 error_messages 保持不变:
password1 = forms.CharField(label='New Label', error_messages={'password_too_short': 'My error message for too short passwords'})
我做错了什么?
【问题讨论】:
-
尝试仅将
'password_too_short': ...重命名为'too_short': ...。 -
不起作用:(
标签: django django-authentication