Django: How to override unique_together error message?
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)
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.",
}
}
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.