我是 Python 新手,尤其是 Django。在尝试深入研究主题时。框架,并运行其官方教程,我遇到了一些令人头疼的错误,其中写着:
Attribute error: 'Poll' object has no attribute 'was_published_recently'
我在 django shell 中输入下一个(由项目目录中的“python manage.py shell”调用):
>>> from polls.models import Poll, Choice
>>> from django.utils import timezone
>>> p = Poll.objects.get(pk=1)
>>> p.was_published_recently()
我得到下一个 shell 输出:
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Poll' object has no attribute 'was_published_recently'"
有人可以帮我弄清楚我在这里做错了什么吗?因为我只是不知道什么会导致这样的错误......(已经用谷歌搜索了这个问题,但没有找到可以解决我的情况的答案)。
我使用:
Django 版本 1.5.1
Python版本2.7.5
这是我的“民意调查”模型代码:
import datetime
from django.utils import timezone
from django.db import models
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
此外,这是我的“管理”文件:
from django.contrib import admin
from polls.models import Choice, Poll
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question', 'pub_date', 'was_published_recently')
admin.site.register(Choice)
admin.site.register(Poll, PollAdmin)
最佳答案
确保使用 4 个空格作为缩进,而不是制表符,制表符会使函数无法识别。
关于django - 将自定义方法添加到模型时发生错误(来自 Django 教程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17797759/