[英]Django Unicode method is not working
I am following the app tutorial on the Django website and using Python 2.7.5 with Django 1.8. 我正在遵循Django网站上的应用程序教程,并在Django 1.8中使用Python 2.7.5。 It suggests users to include a unicode method in the models.py file to return readable output in the python shell.
建议用户在models.py文件中包含unicode方法,以在python shell中返回可读的输出。
I have added the unicode method into the Question and Choice classes as so: 我已经将unicode方法添加到Question和Choice类中:
from django.db import models
import datetime
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days = 1)
def __unicode__(self):
return u"%i" % self.question_text
def __str__(self):
return 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 u"%i" % self.choice_text
def __str__(self):
return choice_text
This is my output from the python shell: 这是我从python shell的输出:
from polls.models import Question, Choice
>>> Question.objects.all()
[<Question: Question object>]
When it really should be this: 真正应该是这样的时候:
>>> Question.objects.all()
[<Question: What's up?>]
I have asked this question before but have not found a solution. 我之前曾问过这个问题,但没有找到解决方案。 Please help!
请帮忙!
You don't need to use both __unicode__
and __str__
. 您不需要同时使用
__unicode__
和__str__
。 In Python 2.7 you just have to use __str__
. 在Python 2.7中,您只需要使用
__str__
。 You can remove the __unicode__
and just use __str__
alone. 您可以删除
__unicode__
而仅使用__str__
。 __unicode__
is for python 3. __unicode__
适用于python 3。
To make the django unicode compatible with python 2 and 3 use the python_2_unicode_compatible decorator. 要使Django unicode与python 2和3兼容,请使用python_2_unicode_compatible装饰器。 Then use
__str__
for the unicodes: 然后将
__str__
用于unicode:
from django.utils import encoding
@encoding.python_2_unicode_compatible
class Question(models.Model):
question_text = models.CharField(max_length=200)
def __str__(self):
return self.question_text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.