[Django]-Django: How to override unique_together error message?

50👍

✅

You can do this since Django 1.7

from django.forms import ModelForm
from django.core.exceptions import NON_FIELD_ERRORS

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

28👍

Update 2016/10/20: See jifeng-yin‘s even nicer answer below for Django >= 1.7

The nicest way to override these error messages might be to override the unique_error_message method on your model. Django calls this method to get the error message whenever it encounters a uniqueness issue during validation.

You can just handle the specific case you want and let all other cases be handled by Django as usual:

def unique_error_message(self, model_class, unique_check):
    if model_class == type(self) and unique_check == ('field1', 'field2'):
        return 'My custom error message'
    else:
        return super(Project, self).unique_error_message(model_class, unique_check)

7👍

For DRF serializers you can use this

from rest_framework import serializers


class SomeSerializer(serializers.ModelSerializer):


    class Meta:
        model = Some
        validators = [
            serializers.UniqueTogetherValidator(
                queryset=model.objects.all(),
                fields=('field1', 'field2'),
                message="Some custom message."
            )
        ]

Here is the original source.

2👍

After a quick check, it seems that unique_together validation errors are hard-coded deep in django.db.models.Model.unique_error_message :

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)

    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field_label = capfirst(opts.get_field(field_name).verbose_name)
        # Insert the error into the error dict, very sneaky
        return _(u"%(model_name)s with this %(field_label)s already exists.") %  {
            'model_name': unicode(model_name),
            'field_label': unicode(field_label)
        }
    # unique_together
    else:
        field_labels = map(lambda f: capfirst(opts.get_field(f).verbose_name), unique_check)
        field_labels = get_text_list(field_labels, _('and'))
        return _(u"%(model_name)s with this %(field_label)s already exists.") %  {
            'model_name': unicode(model_name),
            'field_label': unicode(field_labels)
        }

So maybe you should try to override this method from your model, to insert your own message !?

However, I haven’t tried, and it seems a rather brutal solution ! But if you don’t have something better, you might try…

0👍

Notice: A lot had changed in Django since this answer. So better check other answers…

If what sebpiq is true( since i do not check source code), then there is one
possible solution you can do, but it is the hard way…

You can define a validation rule in your form, as it described here

You can see examples of validation with more than one field, so by using this method, you can define a unique together check before standard django unique check executed…

Or the worst one, you can do a validation in your view before you try to save the objects…

0👍

A better solution could be using validate_unique to raise a ValidationError to replace the error message:

class ModelName(models.Model):
    ...

    class Meta:
        unique_together = ['field_1', 'field_2']
    
    def validate_unique(self, *args, **kwargs):
        super().validate_unique(*args, **kwargs)

        if ModelName.objects.filter(field_1=self.field_1, field_2=self.field_2).exists():
            raise ValidationError(
                ...
            )

Validating objects

Validating objects

There are four steps involved in validating a model:

  1. Validate the model fields – Model.clean_fields()
  2. Validate the model as a whole – Model.clean()
  3. Validate the field uniqueness – Model.validate_unique()
  4. Validate the constraints – Model.validate_constraints()

All four steps are performed when you call a model’s full_clean()
method.

When you use a ModelForm, the call to is_valid() will perform these
validation steps for all the fields that are included on the form. See
the ModelForm documentation for more information. You should only need
to call a model’s full_clean() method if you plan to handle validation
errors yourself, or if you have excluded fields from the ModelForm
that require validation.

-1👍

You might take a look at overriding django/db/models/base.py:Model._perform_unique_checks() in your model.

In that method you can get the “original” errors:

    errors = super(MyModel, self)._perform_unique_checks(unique_checks)

— then modify and return them upwards.

Leave a comment