2016-01-01 88 views
3

我一直在尝试运行此代码,并且它引发缩进错误。无论我尝试什么,结果都是一样的。意外的缩进错误,但缩进看起来正确

如果我在def __str__(self):和其他代码之前删除了缩进,它可以正常工作,但是在输出时,它不显示问题,而是显示“问题对象”。

def __str__(self): 
^ 
IndentationError: unexpected indent 

下面是代码:

from __future__ import unicode_literals 
from django.db import models 
from django.utils.encoding import python_2_unicode_compatible 
from django.utils import timezone 

class Question(models.Model): 
    question_text = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published') 

    def __str__(self): 
     return self.question_text 

    def was_published_recently(self): 
     return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 

class Choice(models.Model): 
    question = models.ForeignKey(Question, on_delete=models.CASCADE) 
    choice_text = models.CharField(max_length=200) 
    votes = models.IntegerField(default=0) 

    def __str__(self): 
     return self.choice_text 
+2

有空格你不混合标签? –

+0

你是如何缩进的?带有制表符或空格? –

+0

仅限使用空间。 4个空间块 –

回答

1

您在混合空格和制表符。假设您的文章中的代码使用的是现实中使用的缩进字符,下面是您的代码实际缩进的示例,其中>---代表一个制表符,.代表一个空格。

from __future__ import unicode_literals 
from django.db import models 
from django.utils.encoding import python_2_unicode_compatible 
from django.utils import timezone 

class Question(models.Model): 
....question_text = models.CharField(max_length=200) 
....pub_date = models.DateTimeField('date published') 

>---def __str__(self): 
....>---return self.question_text 

....def was_published_recently(self): 
>---....return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 

class Choice(models.Model): 
....question = models.ForeignKey(Question, on_delete=models.CASCADE) 
....choice_text = models.CharField(max_length=200) 
....votes = models.IntegerField(default=0) 

>---def __str__(self): 
....>---return self.choice_text 

正如您所看到的,您的缩进不一致。在定义__str__()的两个实例时,您现有的缩进级别为4个空格,但函数定义缩进为1个选项卡。这会导致错误。

按照惯例,Python代码应该只使用空格缩进,从不缩进,因为这个原因。

参见PEP 8,特别是部分“Indentation”和“Tabs or Spaces?