验证 ModelForm 时出现问题
我使用 ModelForm 来创建我的表单。一切正常,除了一件事 - 验证唯一字段。 代码:
class Article(models.Model):
...
title = models.CharField(max_length=255, unique=True, error_messages={'max_length' : 'max translation',
'unique' : 'unique translation',
'required' : 'req translation',})
...
class ArticleForm(ModelForm):
...
title = forms.CharField(max_length=255, min_length=3, error_messages={'required' : 'req translation',
'min_length' : 'min translation',
'max_length' : 'max translation',
'unique' : 'unique translation',})
但是当我使用非唯一标题保存表单时,我没有收到自定义翻译错误,但收到默认错误。如何修复显示我的唯一字段错误?
编辑: 我认为,我找到了非常方便的方法。也许有人会用它:)
def unique_error_message(self, model_class, unique_check):
if 'put_field_name_here' in unique_check and len(unique_check) == 1:
return 'Here goes a custom unique error'
return super(Article, self).unique_error_message(model_class, unique_check)
I use ModelForm to create my form. All works fine except 1 thing - validating the unique field.
Code:
class Article(models.Model):
...
title = models.CharField(max_length=255, unique=True, error_messages={'max_length' : 'max translation',
'unique' : 'unique translation',
'required' : 'req translation',})
...
class ArticleForm(ModelForm):
...
title = forms.CharField(max_length=255, min_length=3, error_messages={'required' : 'req translation',
'min_length' : 'min translation',
'max_length' : 'max translation',
'unique' : 'unique translation',})
But when I save my form with non-unique title I don't get my custom translated error but I get default error. How to fix it, that my unique field error is displayed?
EDIT:
I found, I think, very convenient way to do that. Maybe someone will use it:)
def unique_error_message(self, model_class, unique_check):
if 'put_field_name_here' in unique_check and len(unique_check) == 1:
return 'Here goes a custom unique error'
return super(Article, self).unique_error_message(model_class, unique_check)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有用于自定义验证消息的
唯一
键。我想说,定制是不值得的,但如果必须的话,以下方法应该会有所帮助:此解决方案依赖于未记录的 Django 内部结构,但目前应该可以解决问题。再次强调,我的建议是坚持默认。
There's no
unique
key for customizing validation messages. I'd say it's not worth it to customize, but if you must, following approach should help:This solution relies on undocumented internals of Django, but it should do the trick for now. Again, my recommendation is to stick with default.