I have a data class in Django using the rest framework, that has a string field and a serializer for it.
@dataclass
class Foo:
string_field:str
class FooSerial开发者_StackOverflow中文版izer(DataclassSerializer):
class Meta:
dataclass = Foo
My problem is that, if the string_field is blank, the serializer cannot be validated. The JSON I am calling with:
{'string_field': ''}
And the error:
{'string_field': [ErrorDetail(string='This field may not be blank.', code='blank')]}
Declaring the fields in the serializer and not using a data class is a solution, but I'd prefer to use the data class way if its possible. In my project I am using Django 3.0.5, Python 3.8 and 3.11 of the rest framework.
You need to set allow_blank=True
in the serializers.py
from rest_framework import serializers
class CommentSerializer(serializers.Serializer):
name = CharField(allow_blank=True, max_length=100)
精彩评论