Django教程:意外缩进错误

0 投票
1 回答
8445 浏览
提问于 2025-04-18 16:38

这是我的 model.py 代码:

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 __str__(self):
        return self.question


class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
        def __str__(self):
        return self.choice_text

然后当我运行以下命令时:

python manage.py runserver

我遇到了以下错误:

mjrulesamrat@mjrulesamrat-Lenovo-G570:~/django_local/first_web$ python manage.py runserver 正在验证模型...

在启动的线程中发生未处理的异常,追踪信息(最近的调用在最前面): 文件 "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", 第93行,在 wrapper fn(*args, **kwargs) 文件 "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", 第98行,在 inner_run self.validate(display_num_errors=True) 文件 "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", 第310行,在 validate num_errors = get_validation_errors(s, app) 文件 "/usr/local/lib/python2.7/dist-packages/django/core/management/validation.py", 第34行,在 get_validation_errors for (app_name, error) in get_app_errors().items(): 文件 "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", 第196行,在 get_app_errors self._populate() 文件 "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", 第75行,在 _populate self.load_app(app_name, True) 文件 "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", 第99行,在 load_app models = import_module('%s.models' % app_name) 文件 "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", 第40行,在 import_module import(name) 文件 "/home/mjrulesamrat/django_local/first_web/polls/models.py", 第7行 def str(self): ^ IndentationError: 意外的缩进

我正在使用 Django 1.6 和 Python 2.7。

如果我在这段代码中犯了什么错误,请指导我。因为当我在 Python shell 中运行时,它给我的是 poll 对象,而不是问题。

>>> Poll.objects.all()
[<Poll: Poll object>]

1 个回答

1

注意/修正你在模型方法层级的缩进:

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')

    # HERE 
    def __str__(self):
        return self.question


class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    # AND HERE
    def __str__(self):
        return self.choice_text

撰写回答