问题描述
我试图以Django形式覆盖默认错误消息:
class RegistrationForm(forms.Form):
my_errors = {
'required': 'To pole jest wymagane'
}
email = forms.EmailField(max_length=254, error_messages=my_errors.update({'invalid': 'Podaj prawid?owy adres e-mail'}))
password = forms.CharField(error_messages=my_errors)
firstname = forms.CharField(max_length=80, error_messages=my_errors)
lastname = forms.CharField(max_length=80, error_messages=my_errors)
def clean_email(self):
email = self.cleaned_data['email']
User = get_user_model
try:
User.objects.get(email=email)
raise forms.ValidationError('Adres e-mail jest ju? zaj?ty')
except User.DoesNotExist:
return email
我可以轻松更改“ required”错误消息,因为每个字段都相同。
但是对于电子邮件字段,我希望“无效”消息更加具体,因此我将现有字典与一个包含电子邮件错误消息的字典合并。
但这是行不通的:电子邮件字段返回默认错误消息,而其余字段使用我的错误消息。
请解释为什么会发生以及如何解决它,谢谢
1楼
dict.update
修改dict,并返回None
。
因此,您在声明email
字段时传递error_messages=None
。
您的代码的另一个不良影响是在my_errors
添加了"invalid"
,并且在声明其余字段时传递了扩展的my_errors
。
您需要合并字典而不是使用update
,例如:
class RegistrationForm(forms.Form):
my_errors = {
'required': 'To pole jest wymagane'
}
email = forms.EmailField(max_length=254, error_messages=dict(my_errors, invalid='Podaj prawid?owy adres e-mail'))
password = forms.CharField(error_messages=my_errors)
...