Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django import datetime

Using:

  • Ubuntu 11.04
  • Django 1.3
  • Python 2.7
  • Following the tutorial at Writing your first Django app, part 1

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?

like image 783
Forrest Avatar asked Nov 29 '22 18:11

Forrest


1 Answers

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

like image 77
rolling stone Avatar answered Dec 06 '22 17:12

rolling stone