与this post类似但不同的问题。
Django的新手,我一直在做第一个教程,现在我在第5部分,这是自动化测试。
在按照教程直到“修复Bug”步骤之后,在运行测试时会弹出错误,如下所示:
Creating test database for alias 'default'...
E
======================================================================
ERROR: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/ian/mysite/polls/tests.py", line 18, 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.000s
FAILED (errors=1)
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 QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() returns 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
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
def __str__(self):
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
def __str__(self):
return self.choice_text
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
答案 0 :(得分:1)
您必须 CTRL + D (停止)您的python控制台,然后再次运行python tableView.estimatedRowHeight = 150
tableView.rowHeight = UITableViewAutomaticDimension
shell,最后再次全部导入。现在可以使用。
答案 1 :(得分:0)
尝试以这种方式对我有帮助
polls / models.py
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
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)
# Create your models here.
答案 2 :(得分:0)
除非Django在Model类中做一些魔术(最有可能),否则就python而言,带有pub_date属性的Question对象的创建是不确定的。
答案 3 :(得分:-1)
更改
future_question = Question(pub_date=time)
要
future_question = Question.objects.get(pub_date=time)