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?
The ModelSerializer class has this functionality build-in, at least in djangorestframework>=3.0.0, however if you are using a serializer which doesn't include all of the fields which are affected by your unique_together constrain, then you'll get an IntegrityError when saving an instance which violates it. For example, using the following model:
This validator can be used to enforce the unique=True constraint on model fields. It takes a single required argument, and an optional messages argument: queryset required - This is the queryset against which uniqueness should be enforced. message - The error message that should be used when validation fails.
Therefore it requires Django’s contrib.sessions application. This class stores the message data in a cookie (signed with a secret hash to prevent manipulation) to persist notifications across requests. Old messages are dropped if the cookie data size would exceed 2048 bytes.
This validator should be applied to serializer fields, like so: This validator can be used to enforce unique_together constraints on model instances. It has two required arguments, and a single optional messages argument: queryset required - This is the queryset against which uniqueness should be enforced.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With