两个字段的自定义验证错误 一起唯一 Django



我想编写我自己的验证错误,对于两个唯一的字段

class MyModel(models.Model):
name = models.CharField(max_length=20)
second_field = models.CharField(max_length=10)
#others
class Meta:
unique_together = ('name','second_field')

和我的 forms.py

class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__'
error_messages= {#how to write my own validation error whenever `name and second_field` are unique together }:


name and second_field一起唯一时,如何编写自己的验证错误? 如果两个字段在一起是唯一的,我需要引发一些错误?感谢您的回复

来自 django 文档 -

您可以覆盖来自 NON_FIELD_ERRORS 引发的错误消息 通过将NON_FIELD_ERRORS密钥添加到 error_messages模型窗体的内部元类的字典

from django.core.exceptions import NON_FIELD_ERRORS
from django.forms import ModelForm
class ArticleForm(ModelForm):
class Meta:
error_messages = {
NON_FIELD_ERRORS: {
'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
}
}

您可以按上述方式更新ModelFormmeta类并创建自定义错误消息。

最新更新