我正在处理full tutorial中的Django REST Framework website,并收到一条对我没有意义的错误。
这是python会话:
>>> from snippets.models import Snippet
>>> from snippets.serializers import SnippetSerializer
>>> from rest_framework.renderers import JSONRenderer
>>> from rest_framework.parsers import JSONParser
>>> snippet = Snippet(code='foo = "bar"\n')
>>> snippet.save()
>>> snippet = Snippet(code='print "hello, world"\n')
>>> snippet.save()
>>> serializer = SnippetSerializer(snippet)
>>> serializer.data
ReturnDict([('pk', 3), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
>>> content = JSONRenderer().render(serializer.data)
>>> content
'{"pk":3,"title":"","code":"print \\"hello, world\\"\\n","linenos":false,"language":"python","style":"friendly"}'
>>> from rest_framework.compat import BytesIO
>>> stream = BytesIO(content)
>>> data = JSONParser().parse(stream)
>>> serializer = SnippetSerializer(data=data)
>>> serializer.is_valid()
False
>>> serializer.errors
ReturnDict([('title', [u'This field may not be blank.'])])
>>>
以下是序列化程序的相关行:
title = serializers.CharField(
required=False,
max_length=100,
)
......以及模型中的相关行:
title = models.CharField(max_length=100, blank=True, default='')
模型和序列化程序都允许“title”的空值,但错误表示空值无效。有人可以解释为什么我会看到这个吗?
答案 0 :(得分:0)
这里应该为你做这件事:)
看看django休息框架
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py
具体而言,行504具有以下内容:
def __init__(self, **kwargs):
self.allow_blank = kwargs.pop('allow_blank', False)
max_length = kwargs.pop('max_length', None)
min_length = kwargs.pop('min_length', None)
super(CharField, self).__init__(**kwargs)
if max_length is not None:
message = self.error_messages['max_length'].format(max_length=max_length)
self.validators.append(MaxLengthValidator(max_length, message=message))
if min_length is not None:
message = self.error_messages['min_length'].format(min_length=min_length)
self.validators.append(MinLengthValidator(min_length, message=message))
按如下方式更改实际上在审核教程时,是否可能错过了将serialization.CharField
:allow_blank
添加到需要它的其他部分...具体来说{ {1}}
SnippetSerializer
正在运行的验证是
title = serializers.CharField(
required=False,
max_length=100,
allow_blank=True,
)
您可以看到检查CharField是否为空,而不是是否需要。它是唯一一个调用空白错误消息的地方。