__unicode__方法的Django模型错误

时间:2014-03-20 19:29:55

标签: python django

我在Django项目中有以下python代码:

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

当我运行python manage.py validate命令时,我收到以下错误:

 def __unicode__(self)
                    ^
SyntaxError: invalid syntax

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

你忘记了缩进和“:” 它应该是:

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

答案 1 :(得分:2)

您忘记了:

更改

def __unicode__(self)

def __unicode__(self):

另外,请注意缩进。

def __unicode__(self): 
    return u'{0}'.format(self.choice_text)
    #^ Indentation