Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django tutorial unicode not working

Tags:

I have the following in my models.py

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   

but when I enter

from polls.models import Poll, Choice Poll.objects.all() 

I don't get Poll: What's up? but Poll: Poll object

Any ideas?

like image 264
Sharon Dankwardt Avatar asked Apr 20 '13 15:04

Sharon Dankwardt


1 Answers

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.

like image 174
Alasdair Avatar answered Sep 18 '22 23:09

Alasdair