一起唯一的两个字段的自定义验证错误 [英] custom validation error for two fields unique together django

查看:47
本文介绍了一起唯一的两个字段的自定义验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i want to write my own validation error , for two fields unique together

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')

和我的表格。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和second_field 唯一时,验证错误?如果两个字段都是唯一的,则
i需要引发一些错误?感谢答复

how to write my own validation error whenever name and second_field are unique together? i need to raise some error if both fields were unique together ?thanks for replying

推荐答案

来自Django 文档-


您可以通过将NON_FIELD_ERRORS键添加到ModelForm的内部元类的
error_messages字典中来覆盖由
模型验证引发的NON_FIELD_ERRORS错误消息

You can override the error messages from NON_FIELD_ERRORS raised by model validation by adding the NON_FIELD_ERRORS key to the error_messages dictionary of the ModelForm’s inner Meta class


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.",
            }
        }

您可以更新 ModelForm 类,并创建自定义错误消息。

You can update your ModelForm meta class as above and create a custom error message.

这篇关于一起唯一的两个字段的自定义验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆