Reputation: 153
I am trying to use unique_together for two fields (email and type) for Meta for a model, but the the error message is always "The fields email, type must make a unique set." What is the best way to override the unique_together error message?
Upvotes: 6
Views: 4317
Reputation: 226
You can use UniqueTogetherValidator
on your serializer (see http://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidator).
Then, you can override the displayed message at initialization:
UniqueTogetherValidator(message='Your custom message', fields=(field1, field2,))
Unfortunately, the error message from Django for a unique_together ValidationError
is hardcoded. If you want to change the error message, a way I can think of is to override the unique_error_message
method of your model.
def unique_error_message(self, model_class, unique_check):
error = super().unique_error_message(model_class, unique_check)
# Intercept the unique_together error
if len(unique_check) != 1:
error.message = 'Your custom message'
return error
Upvotes: 11