2013-04-20 106 views
19

在我的models.pyDjango的教程的Unicode不工作

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() 

我不明白 投票:這是怎麼回事? 但是 投票:投票對象

任何想法?

回答

34

Django的1.5具有用於Python 3的實驗支持,但Django 1.5 tutorial被用於Python 2.X寫成:

本教程是爲Django的1.5和Python 2.x的書面如果Django版本不匹配,可以參考您的Django版本教程或將Django更新爲最新版本。如果您使用的是Python 3.x,請注意,您的代碼可能需要與本教程中的內容有所不同,並且只有在您知道自己在使用Python 3.x時才應繼續使用本教程。

在Python 3中,您應該定義一個__str__方法而不是__unicode__方法。有一個裝飾python_2_unicode_compatible它可以幫助你編寫代碼在Python 2工程和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方法在Porting to Python 3文檔部分。

+0

我重新回到了每個標籤重新保存的4個空格的全部空格,重新啓動了shell無濟於事。仍然不能正常工作 – 2013-04-20 17:39:57

+0

與我使用的python版本有關係嗎?我有3.2.3 – 2013-04-20 17:42:05

+2

是的,這解釋了它。這是因爲你正在使用Python 3.查看我更新的答案。 – Alasdair 2013-04-20 17:50:43