Stuck in Django's official tutorial

I just started to learn Python and started to learn Django a bit. So I copied this piece of code from the tutorial:

    # 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_today(self):
        return self.pub_date.date() == datetime.date.today()

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def ___unicode__(self):
        return self.choice   #shouldn't this return the choice

When I play with it in the shell, I just get the “question” of the Poll object, but for some reason it won’t return the “choice” of the Choice objects. I do not see the difference. My output on the shell is as follows:

>>> Poll.objects.all()
[<Poll: What is up?>]
>>> Choice.objects.all()
[<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>]
>>>

I was expecting Choice objects to return something other than a "Choice object". Does anyone have any idea where I failed and what I should learn?

EDIT: A way to make me feel like an idiot. Yes, these three underscores were a problem. I have been looking at this for about an hour.

+3
source share
4 answers

"unicode__" Choice, , Poll, :

def __unicode__(self):
    return u'%s' % self.choice
+8

Unicode- . :

def __unicode__(self):
    return u'%s' % self.choice
+4

Edit:

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def ___unicode__(self):
        return self.choice   #shouldn't this return the choice

To:

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def __unicode__(self):
        return self.choice   #shouldn't this return the choice

You had too many underscores in the second definition __unicode__

+3
source

The official Django book is a bit dated. But the paragraph comments are really helpful. It must be two underscores:

___unicode__(self):

it should be __unicode__(self):

+2
source

Source: https://habr.com/ru/post/1709283/


All Articles