2014-12-05 40 views
0

我正在通過full tutorialDjango REST Framework website工作,並得到一個對我來說沒有意義的錯誤。Django REST框架教程給出了錯誤,不明白爲什麼

這裏的蟒蛇會議:

>>> 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='') 

的模型和序列化器都允許爲'標題'的空值,但錯誤表明一個空值i這是無效的。有人可以解釋爲什麼我可能會看到這個?

回答

0

這裏這應該爲你做:)

看看Django的REST框架專道504

https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py

它具有如下:

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到需要它的另一個部分...具體的SnippetSerializer

title = serializers.CharField(
    required=False, 
    max_length=100, 
    allow_blank=True, 
    ) 

驗證正在運行的是

def run_validation(self, data=empty): 
     # Test for the empty string here so that it does not get validated, 
     # and so that subclasses do not need to handle it explicitly 
     # inside the `to_internal_value()` method. 
     if data == '': 
      if not self.allow_blank: 
       self.fail('blank') 
      return '' 
     return super(CharField, self).run_validation(data) 

正如你所看到的檢查,看是否CharField是空白,如果需要或不需要的話。這是空白錯誤消息被調用的唯一地方。

+0

謝謝!我看到教程已經從昨天開始更新,顯然是爲了解決這個問題(以及其他一些問題)。在我開始編寫這個問題之前,它已經改變了,但是我仍然在查看不包含allow_blank參數的(稍微老)版本。 – seawolf 2014-12-05 18:20:33

相關問題