ni8mr
ni8mr

Reputation: 1785

Problems while following the instructions of Django official documentation

I am following Django official tutorial of Writing your first Django app, part 1. There at last para i have to give the following command:

q.was_published_recently()

And the output should be:

True

Instead, i have:

False

Here is my models.py file:

import datetime

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

# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return u'%s' % (self.question_text)

    def was_published_recently(self):
        return self.pub_date >= timezone.now()-datetime.timedelta(days=1)

    class Choice(models.Model):
        question = models.ForeignKey(Question)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

I am guessing may be i am having problem at timedelta function. I am not sure though.

N.B.: the exact steps of the documentation are:

>>> from polls.models import Question, Choice
>>> Question.objects.all()
[<Question: What's up?>]
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up?>]


>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>

>>> Question.objects.get(id=2)
Traceback (most recent call last):
     ...
DoesNotExist: Question matching query does not exist.

>>> Question.objects.get(pk=1)
<Question: What's up?>

>>> q = Question.objects.get(pk=1)

>>> q.was_published_recently()
True

Upvotes: 0

Views: 852

Answers (2)

chsymann
chsymann

Reputation: 1670

According to the method name I would say that False is the correct return value in this case. The method should return True if the Question is less old than one day. In your case the pub_date is a date more older than one day so it was not "published recently" so the method returns False. If you change your date to now with q.pub_date = timezone.now() and then save with q.save(), q.was_published_recently() should return True for exactly one day.

Upvotes: 1

ni8mr
ni8mr

Reputation: 1785

At last, I have found the problem. It was in the definition of the was_published_recently() method. It should be <= instead of >=.

Here is the redefined method:

def was_published_recently(self):
    return self.pub_date <= timezone.now()-datetime.timedelta(days=1)

Previously, the method was testing if the pub_date is greater or equal than the yesterday which was wrong.

Now, it is testing if the pub_date is less or equal than the yesterday, which is right.

Upvotes: 0

Related Questions