卡在官方的Django教程上

2024-03-28 19:16:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始学习Python,也开始研究Django。所以我从教程中复制了这段代码:

    # 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

当我在shell中使用它时,我只得到Poll对象的“question”,但由于某些原因,它不会返回choice对象的“choice”。我看不出有什么不同。我在shell上的输出如下所示:

^{pr2}$

我希望Choice对象返回除“Choice object”之外的其他内容。有人知道我在哪里失败了,我应该调查什么吗?在

编辑:让我觉得自己像个白痴。是的,三个下划线就是问题所在。我已经看了一个小时了。在


Tags: 对象selfdatemodelreturnmodelsdeflength
3条回答

Unicode方法的下划线太多。应改为:

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

在Choice类的“unicode”前面有三个下划线,在Poll类中应该只有两个下划线,如下所示:

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

更改:

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

收件人:

^{pr2}$

第二个__unicode__定义中的下划线太多

相关问题 更多 >