Search code examples
djangodjango-modelsdjango-tests

Django: object has no attribute 'was_published_recently'


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

Solution

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