Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 307
djreenykev Avatar asked Apr 10 '18 10:04

djreenykev


People also ask

Why am I getting integrityerror when saving a unique_together constrain?

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:

How do I enforce the unique=true constraint on model fields?

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.

How to persist email notifications across Django sessions?

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.

How to enforce unique_together constraints on Serializer fields?

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.


1 Answers

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
like image 179
Netizen29 Avatar answered Oct 22 '22 03:10

Netizen29