Django:对象没有属性'was_published_recently' [英] Django: object has no attribute 'was_published_recently'
本文介绍了Django:对象没有属性'was_published_recently'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Django的新手,我一直在做第1篇教程,现在是第5部分,它是自动化测试.
New to Django, I've been doing the 1st tutorial and I'm at part 5 now, which is automated testing.
按照本教程进行操作,直到步骤"修复错误",当我运行测试时,它会弹出一个错误,如下所示:
After following the tutorial until step "Fixing the Bug", it pops up an error when I run the test, as follows:
Traceback (most recent call last):
File "D:\Python\Django\ui1\polls\tests.py", line 13, in test_was_published_recently_with_future_question
self.assertIs(future_question.was_published_recently(), False)
AttributeError: 'Question' object has no attribute 'was_published_recently'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
Destroying test database for alias 'default'...
在教程页面中,它在测试中没有显示错误.
Whereas in the tutorial page, it shows no error in the testing.
Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Destroying test database for alias 'default'...
这是我的代码.
tests.py
import datetime
from django.utils import timezone
from django.test import TestCase
from .models import Question
class QuestionMethodTests(TestCase):
def test_was_published_recently_with_future_question(self):
#should return False for questions whose pub_date is in the future.
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False)
models.py
from django.db import models
class Question(models.Model):
question_text= models.CharField(max_length=200)
pub_date=models.DateTimeField('date published')
def __str__(self):
return self.question_text
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
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
推荐答案
您需要将函数移到现在不属于Question类的类中.
You need to move your function inside class it doesn't belong to the Question class now.
class Question(models.Model):
...
def was_published_recently(self):
...
这篇关于Django:对象没有属性'was_published_recently'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文