custom validation error for two fields unique together django

左心房为你撑大大i 提交于 2020-07-23 06:14:20

问题


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

and my 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 }:
        
     

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


回答1:


From django docs -

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

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



来源:https://stackoverflow.com/questions/62726675/custom-validation-error-for-two-fields-unique-together-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!