Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-serializervalidationerror

Django Rest Framework - Custom error messages - Serializer vs. Model


:) Hello!

I'm currently facing a problem that I am not being able to solve by searching the documentation or other questions, if someone can help I would be very grateful.

The problem is relatively of simple: I am adding custom messages for validation errors that come up when posting a new object, but I'd like to do it in one place only: inside model OR inside serializer.

For the sake of this example and my use case, I am talking only about unique and max_length validations.

  • Defining error_messages=errors_dict inside the model fields currently only changes the unique validation error message, displaying the default for max_length.

  • The opposite happens when I set it inside the serializer, using extra_kwargs inside Meta. It only changes the max_length validation error message.

Does anyone know what I am missing here? Is it possible to set the error_messages in only one place?

Thank you!


Here are some code snippets, if it helps:

errors in the below examples is the same dictionary, containing both keys (unique and max_length).

  • Inside Model, working only for the unique validation:
class User(AbstractUser, SplintModel):
    (...)
    cpf = models.CharField('CPF', blank=False, max_length=11, unique=True, error_messages=errors)
  • Inside Serializer, working only for the max_length validation:
class UserSerializer(serializers.ModelSerializer):
    (...)
    class Meta:
        model = User
        (...)

        extra_kwargs = {
            "cpf": {"error_messages": errors}
        }

Solution

  • try this in your serializers.py:

    from rest_framework.validators import UniqueValidator
    
        extra_kwargs = {
           'cpf': { 
                    {
                      'error_messages' : {"max_length": "your error"},
                      'validators': [
                          UniqueValidator(
                             queryset=User.objects.all(),
                             message="write your error message here"
                    )
                 ]
            }
         }