djreenykev
djreenykev

Reputation: 153

Override unique_together error message in Django Rest Framework

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

Answers (1)

Netizen29
Netizen29

Reputation: 226

Option 1: At serialization

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

Option 2: Model validation

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

Related Questions