如何在自定义UserChangeForm中覆盖用户名的django'unique'错误消息 [英] How to override django 'unique' error message for username in custom UserChangeForm
问题描述
我想覆盖默认的具有该用户名的用户已经存在。在我自定义的 UserChangeForm
表单中输入现有用户名时显示错误消息。使用Django版本:1.6.1
I'm trying to override the default "A user with that Username already exists." error message displayed when entering an existing username in my custom UserChangeForm
form. Django version used: 1.6.1
这是我的代码:
class CustomUserChangeForm(forms.ModelForm):
username = forms.RegexField(
label="User name", max_length=30, regex=r"^[\w.@+-]+$",
error_messages={
'invalid': ("My message for invalid"),
'unique': ("My message for unique") # <- THIS
}
)
class Meta:
model = get_user_model()
fields = ('username', 'first_name', 'last_name', 'email',)
但是,如果我使用此代码输入现有的用户名,我仍然会获得默认值此用户名已存在。信息。请注意,输入错误的用户名(无效的字符)时,会显示自定义的我的无效信息。
But if I enter an existing username with this code, I still get the default "A user with that Username already exists." message. Note that the custom "My message for invalid" is displayed when entering a wrong username (with invalid characters).
推荐答案
code>唯一错误消息无法在表单域级别进行自定义,来自 docs :
class CharField(** kwargs)
class CharField(**kwargs)
...
错误消息密钥:required,max_length,min_length
Error message keys: required, max_length, min_length
。 ..
class RegexField(** kwargs)
class RegexField(**kwargs)
...
错误消息密钥:必需,无效
Error message keys: required, invalid
所以,总结一下,对于你的
c c $ c>,
min_length
错误消息是可定制的。
So, to summarize, for your username
field only required
, invalid
, max_length
, min_length
error messages are customizeable.
您只能设置唯一
模型字段级别的错误消息(请参阅来源)。
You can only set unique
error message on a model field level (see source).
另请参阅相关票。
另请参阅 django.contrib.auth.forms.UserCreationForm (注意自定义 duplicate_username
错误消息) - 自定义错误消息可能是
Also see how django.contrib.auth.forms.UserCreationForm was made (pay attention to custom duplicate_username
error message) - custom error message could be an option for you too.
希望有所帮助。
这篇关于如何在自定义UserChangeForm中覆盖用户名的django'unique'错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!