Using:
Hi, I'm a python beginner, coming from a PHP background, so I apologize if this is a stupid question. I'm getting stuck when trying to call the p.was_published_today(). It outputs this error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/path/to/mysite/polls/models.py", line 12, in was_published_today
pub_date = models.DateTimeField('date published')
NameError: global name 'datetime' is not defined
But the code in my models.py looks (to me) exactly as I should have it according to the tutorial:
from django.db import models
import datetime
# Create your models here.
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_today(self):
return self.pub_date.date() == datetime.date.today()
# other code but not relevant to the error
I've seen others around here asking about a very very similar issue with the datetime not working in this tutorial, but none of the answers to them actually helped me get it working. It works in the python interpreter but not in the script. I'm very confused & I've been working on this detail for 45 minutes. Does anybody have a clue?
Make sure you import datetime in your view. Add:
import datetime
to your Views.py page. There was a ticket that was once opened for this issue:
https://code.djangoproject.com/ticket/5668
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