Using __str__() method in Django on Python 2

django, django-models, python, python-2.7

Solution

To keep the code compatible between py2 and py3, a better way is to use the decorator `python_2_unicode_compatible`. This way you can keep the str method:

from django.db import models
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Question(models.Model):
# ...
    def __str__(self):              # __unicode__ on Python 2
        return self.question_text

@python_2_unicode_compatible
class Choice(models.Model):
# ...
    def __str__(self):              # __unicode__ on Python 2
        return self.choice_text

Reference: https://docs.djangoproject.com/en/1.8/topics/python3/#str-and-unicode-methods

Django provides a simple way to define str() and unicode() methods that work on Python 2 and 3: you must define a str() method returning text and to apply the python_2_unicode_compatible() decorator.

...

This technique is the best match for Django’s porting philosophy.

Problem

I am Learning Django using the Django project tutorial. Since I use python 2.7 I am unable to implement the following in python 2.7: ``` from django.db import models class Question(models.Model): # ... def __str__(self): # __unicode__ on Python 2 return self.question_text class Choice(models.Model): # ... def __str__(self): # __unicode__ on Python 2 return self.choice_text ```

Original source