Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django unicode方法不起作用_Django_Python 2.7_Unicode - Fatal编程技术网

Django unicode方法不起作用

Django unicode方法不起作用,django,python-2.7,unicode,Django,Python 2.7,Unicode,我正在关注Django网站上的应用程序教程,并将Python2.7.5与Django 1.8一起使用。它建议Python 2.7用户在models.py文件中包含unicode方法,以在Python shell中返回可读的输出 我已将unicode方法添加到问题和选择类中,如下所示: 这是我在python shell中的输出: 从polls.models导入问题,选项 >>>问题.对象.全部() [] >>> 应该是这样的: >Question.objects.all() [无论是最近发布的

我正在关注Django网站上的应用程序教程,并将Python2.7.5与Django 1.8一起使用。它建议Python 2.7用户在models.py文件中包含unicode方法,以在Python shell中返回可读的输出

我已将unicode方法添加到问题和选择类中,如下所示: 这是我在python shell中的输出:

从polls.models导入问题,选项
>>>问题.对象.全部()
[]
>>> 
应该是这样的:

>Question.objects.all()

[无论是最近发布的
还是
\uuuuuUnicode\uuuu
方法都不在问题类中。缩进很重要:确保它们缩进到与字段相同的级别。

实际上,您还应该定义一个
\uuuu str\uuuu
方法。
\uuUnicode\uuuUnicode>将用于显式unicode调用。

最好使用
django.utils.encoding
中的
python\u 2\u unicode\u compatible
decorator,您将只定义
\u str\u
方法

@python_2_unicode_compatible
class A(object):
    def __str__(self):
        # your code

此外,该方法还与python3兼容。

我已经找到了正确的方法(我将在virtualenv中使用Python2.7.11和django 1.9.2完成教程):

现在,从项目目录的底部运行manage.py文件,如下所示:

$ python manage.py shell
这会加载IPython,但会为您设置所有适当的环境变量,因此很容易导入您的应用程序(假设我们称之为“polls”,我相信这就是教程所称的)。现在让我们从 我们刚刚用manage.py调用的IPython解释器:

>>> from polls.models import Question, Choice
>>> Question.objects.all()
[]
>>> q = Question(question_text="I am now unicode!")
>>> q.save()
>>> Question.objects.all()
[<Question: I am now unicode!>]
>>来自polls.models导入问题,选项
>>>问题.对象.全部()
[]
>>>q=问题(问题=“我现在是unicode!”)
>>>q.保存()
>>>问题.对象.全部()
[]

缩进与代码中的缩进相同还是错误?根据问题,unicode函数在您的类之外对不起!我的文件中有正确的缩进,但是,当它粘贴到这里时,缩进发生了变化。它仍然不起作用。我像这样添加了它,甚至重新启动了python shell。@Akisame
def__str(self):返回问题文本
@python_2_unicode_compatible
class A(object):
    def __str__(self):
        # your code
from __future__ import unicode_literals
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)

    def __unicode__(self):
        return unicode(self.question_text)

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

    def __unicode__(self):
        return unicode(self.choice_text)
$ python manage.py shell
>>> from polls.models import Question, Choice
>>> Question.objects.all()
[]
>>> q = Question(question_text="I am now unicode!")
>>> q.save()
>>> Question.objects.all()
[<Question: I am now unicode!>]