'Django Serializer field validator not being called
Serializer field validator not being called seems to be a common problem but I cannot find the right solution. I have a normal (NON-MODEL) serializer with a URLField and a custom validator for the field. The field validator is not being hit when running is_valid(), instead the builtin URLValidator is being called.
Here is the custom validator (only to avoid http:// not included error):
class OptionalSchemeURLValidator(URLValidator):
def __call__(self, value):
if "://" not in value:
value = "http://" + value
super(OptionalSchemeURLValidator, self).__call__(value)
Here is the serializer:
from rest_framework.serializers import Serializer
class DeveloperAccessTokenSerializer(Serializer):
token = CharField(read_only=True)
company_website = URLField(
required=False,
validators=[OptionalSchemeURLValidator()],
)
def create(self, validated_data):
self.token = jwt.encode(
jwt_payload, settings.SECRET_KEY, algorithm="HS256"
)
self.company_website = validated_data.get("company_website", None)
return self.company_website
Here is how the serializer is being used:
def post(self, request, *args, **kwargs):
context = {"request": request}
ser = self.serializer_class(data=request.data, context=context)
ser.is_valid(raise_exception=True)
token = ser.save()
return Response(token, status=HTTP_201_CREATED)
Validation error is being raised on is_valid():
rest_framework.exceptions.ValidationError: {'company_website': [ErrorDetail(string='Enter a valid URL.', code='invalid')]}
Input value for the field is
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
