我正在尝试覆盖ModelForm中字段的“唯一”错误消息。我正在尝试关注Django 1.6的docs,但我无法让它工作。非常简单的东西,我有:
models.py:
class EmailAddress(Model):
"""An email address."""
address = EmailField(unique=True)
def __unicode__(self):
return self.address
views.py:
class EmailAddressForm(ModelForm):
class Meta:
model = EmailAddress
fields = {'address'}
error_messages = {
'address': {
u'unique': _('That address has already been added.'),
}
}
如果我输入重复的电子邮件,我会:
emailaddress_form.errors = {'address': [u'Email address with this Address already exists.']}.`
我在源代码中进行了挖掘,据我所知,我正在将error_messages
dict正确地传递到被django.forms.models.fields_for_model
函数调用的位置。元类。希望我错过了一些明显的东西。有什么建议吗?
答案 0 :(得分:0)
在EmailAddressForm类上创建方法“clean_address”,希望这将解决您的问题。
def clean_address(self):
"""Prevent duplicate email addresses."""
if 'email' in self.changed_data:
if self.Meta.model.all().filter('address =', self.cleaned_data['address']).count():
raise forms.ValidationError('Email address with this Address already exists.: %s.' %
self.cleaned_data['address'])
return self.cleaned_data['address']
答案 1 :(得分:0)
试试这个: -
将地址字段更改为: -
address = models.EmailField(unique = True,error_messages = {'unique':“该地址已被添加。”})