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! :-)
You need to import Timezone first from Django utils and after that you need to import datetime.
from django.db import models
from django.utils import timezone
import datetime
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With