Search code examples
djangovalidationdjango-formsdata-cleaning

custom validation error for two fields unique together django


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


Solution

  • 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.