Django教程unicode不工作 [英] Django tutorial unicode not working

查看:126
本文介绍了Django教程unicode不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的models.py中有以下内容

I have the following in my models.py

import datetime
from django.utils import timezone
from django.db import models

# Create your models here.
class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question

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

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

    def __unicode__(self):
        return self.choice_text  

,但是当我输入

from polls.models import Poll, Choice
Poll.objects.all()

我不会得到
投票:什么?

投票:投票对象

I don't get Poll: What's up? but Poll: Poll object

任何想法?

推荐答案

Django 1.5对Python 3有实验支持,但 Django 1.5教程是为Python编写2.X:

Django 1.5 has experimental support for Python 3, but the Django 1.5 tutorial is written for Python 2.X:


本教程是为Django 1.5和Python 2.x编写的。如果Django版本不匹配,您可以参考Django版本的教程,或者将Django更新到最新版本。如果您使用的是Python 3.x,请注意,您的代码可能需要与教程中的内容不同,只有当您知道您在使用Python 3.x时您应该继续使用教程。

This tutorial is written for Django 1.5 and Python 2.x. If the Django version doesn’t match, you can refer to the tutorial for your version of Django or update Django to the newest version. If you are using Python 3.x, be aware that your code may need to differ from what is in the tutorial and you should continue using the tutorial only if you know what you are doing with Python 3.x.

在Python 3中,您应该定义一个 __ str __ 方法而不是 __unicode __ 方法。有一个装饰器 python_2_unicode_compatible 可以帮助您编写适用于Python 2和3的代码。

In Python 3, you should define a __str__ method instead of a __unicode__ method. There is a decorator python_2_unicode_compatible which helps you to write code which works in Python 2 and 3.

from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible

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

    def __str__(self):
        return self.question

有关详细信息,请参阅 str和unicode方法 //docs.djangoproject.com/en/1.5/topics/python3/#str-and-unicode-methods\">移植到Python 3 文档。

For more information see the section str and unicode methods in the Porting to Python 3 docs.

这篇关于Django教程unicode不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆