Django: object has no attribute 'was_published_recently'

房东的猫 提交于 2019-12-12 04:17:05

问题


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

Here's my code.

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

回答1:


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):
        ...



回答2:


In models.py add:

from django.db import models
from django.utils import timezone


来源:https://stackoverflow.com/questions/40424854/django-object-has-no-attribute-was-published-recently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!