TypeError:强制转换为Unicode:需要字符串或缓冲区,找到NoneType

时间:2016-01-28 10:54:12

标签: python django models

我正在浏览Django教程,第2部分: https://docs.djangoproject.com/en/1.9/intro/tutorial02/ 在我们为一个问题附加几个选择的地方

# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
[]

我收到了一个错误:

/home/paulmad/env/local/lib/python2.7/site-packages/IPython/lib/pretty.pyc in _repr_pprint(obj, p, cycle)
    692     """A pprint that just redirects to the normal repr function."""
    693     # Find newlines and replace them with p.break_()
--> 694     output = repr(obj)
    695     for idx,output_line in enumerate(output.splitlines()):
    696         if idx:

/home/paulmad/env/local/lib/python2.7/site-packages/django/db/models/query.pyc in __repr__(self)
    235         if len(data) > REPR_OUTPUT_SIZE:
    236             data[-1] = "...(remaining elements truncated)..."
--> 237         return repr(data)
    238 
    239     def __len__(self):

/home/paulmad/env/local/lib/python2.7/site-packages/django/db/models/base.pyc in __repr__(self)
    457     def __repr__(self):
    458         try:
--> 459             u = six.text_type(self)
    460         except (UnicodeEncodeError, UnicodeDecodeError):
    461             u = '[Bad Unicode data]'

TypeError: coercing to Unicode: need string or buffer, NoneType found

以下是我的模特:

from __future__ import unicode_literals

import datetime
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
# Create your models here.

@python_2_unicode_compatible
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def __unicode__(self):
        return unicode(self.quesion_text) or u''

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

@python_2_unicode_compatible
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        self.choice_text

    def __unicode__(self):
        return unicode(self.choice_text) or u''

Django 1.9.1,如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

在您的模型中,更新名为__str__(self)的方法。

class Choice(models.Model):
    choice_text = models.CharField(max_length=255, null=True)

    def __str__(self):
       return self.choice_text if self.choice_next else ''

答案 1 :(得分:0)

事实上,只需要在self.choice_text之前添加返回 str

答案 2 :(得分:0)

您使用的是@python_2_unicode_compatible,因此您无需定义__unicode____str__

如果您使用不带__unicode__装饰器的Python 2,则只需定义@python_2_unicode_compatible

您应该将模型更改为:

@python_2_unicode_compatible
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

@python_2_unicode_compatible
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        self.choice_text

您的方法中不应该使用unicode(self.choice_text) or u''之类的代码 - 当值未设置时,CharField应该默认为空字符串。