[Django]-Django tutorial unicode not working

40👍

Django 1.5 has experimental support for Python 3, but the Django 1.5 tutorial is written for Python 2.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.

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

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

Leave a comment