:) 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_dictinside the model fields currently only changes theuniquevalidation error message, displaying the default formax_length.The opposite happens when I set it inside the serializer, using extra_kwargs inside Meta. It only changes the
max_lengthvalidation 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}
}
try this in your serializers.py: