Yogi
Yogi

Reputation: 3

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. It suggests users to include a unicode method in the models.py file to return readable output in the python shell.

I have added the unicode method into the Question and Choice classes as so:

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:

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!

Upvotes: 0

Views: 339

Answers (2)

User Rik
User Rik

Reputation: 106

To make the django unicode compatible with python 2 and 3 use the python_2_unicode_compatible decorator. Then use __str__ for the unicodes:

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

Upvotes: 1

WutWut
WutWut

Reputation: 1234

You don't need to use both __unicode__ and __str__. In Python 2.7 you just have to use __str__ . You can remove the __unicode__ and just use __str__ alone. __unicode__ is for python 3.

Read more about it in the docs here

Upvotes: 2

Related Questions