我使用Django 1.6
。我像这样编辑models.py
:
(我点这个链接:tutorial01)
from django.db import models
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 shell
我的错误是:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
399, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 242,
in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 285,
in execute
output = self.handle(*args, **options)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 415,
in handle
return self.handle_noargs(**options)
File "C:\Python27\lib\site-packages\django\core\management\commands\shell.py",
line 70, in handle_noargs
get_models()
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 232, in
get_models
self._populate()
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 75, in
_populate
self.load_app(app_name, True)
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 99, in
load_app
models = import_module('%s.models' % app_name)
File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 40, in im
port_module
__import__(name)
File "G:\Programing\Django\Project\mysite\polls\models.py", line 7
def __str__(self):
^
IndentationError: unexpected indent
我认为这一行中的某些事情是def __str__(self): return self.question
rong?
答案 0 :(得分:1)
您的def __str__
需要与班级其他人的缩进级别相同。确保类主体和def的内容都缩进4个空格。您正在混合制表符和空格缩进,这会使解析器混淆。避免使用标签进行缩进 - 只需坚持每个级别4个空格。当您按Tab键时,您的编辑器应该可以选择插入4个空格。
答案 1 :(得分:0)
首先检查文本编辑器。对我来说,我使用了Notepad ++,其中Notepad ++中的选项卡与Python选项卡中的选项卡不同。因此,在Python自己的文本编辑器中编辑代码会有所帮助。
其次在
def str(self):之前删除行差距 您的代码应如下所示:
from django.db import models 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