Hi!
summarize the problem
I have a Django Rest Framework backend, on which I want to do a simple thing: change default validation message:
'max_length': _('Ensure this field has no more than {max_length} characters.'),
To a custom one like
'max_length': 'I am happy to see you {max_length}.'
methods that failed are on the bottom of this post
minimal example:
You can pull a minimal example from git repo, and run tests by calling this file.
from django.contrib.auth.models import (
AbstractBaseUser,
PermissionsMixin,
)
from django.db import models
from rest_framework import serializers
class User(AbstractBaseUser, PermissionsMixin):
name = models.CharField("Name", max_length=42, null=True,
error_messages={'max_length':"I am happy to see you {max_length}."})
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["name"]
extra_kwargs = {
"name": {"required": True, "allow_blank": False, "allow_null": False},
}
class TestUserSerializer:
def test_name() -> None:
data = {
"name": "A" * 43,
}
serializer = UserSerializer(data=data)
assert serializer.is_valid() is False
assert str(serializer.errors["name"][0]) == "I am happy to see you 42."
error messages seem to be ignored.
What failed:
- (main)
error_messagesas a CharField argument (as shown in example) - (experiment_1) based on this issue, I tried setting up a validatior argument for CharField, like:
validators=[MaxLengthValidator(42, message="I am happy to see you {max_length}.")] - (experiment 2A 2B) based on a very similar stack question I tried adding a custom
CharFieldclass. Maybe I didnt understand their solution, because inheriting fromfields.CharFielddidnt allow me to set stuff into init method (I usemodel.CharField, they usefield.Charfield. It didnt work either way. - Based on this issue I started wondering if this is even doable.
- (experiment 3) Writing a custom validation method
def validate_name(self, value):insideUserSerializer. It is also ignored.