djangodatetimedjango-modelstimezone

Django - can not get a time function (timezone, datetime) to work properly, Getting ErrorName message: global name not defined


I'm a Django newbie,

I am following a tutorial and I had to create two models shown below:

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

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question

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


class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField()

    def __unicode__(self):
        return self.choice_text

The following code is from the tutorial. I should get True.

# Make sure our custom method worked.
>>> p = Poll.objects.get(pk=1)
>>> p.was_published_recently()
True

But when I type (same lines as tutorial):

>>> p = Poll.objects.get(pk=1)
>>> p.was_published_recently()

I get the following error message:

models.py line 12 in was_published_recently
NameError: global name 'datetime' is not defined..

I imported datetime and timezone... I don't see why I get that error message.

Any help will be appreciated! :-)


Solution

  • Couldn't reproduce the problem, your code works for me. You could try with something like this:

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