开发者

Django import datetime

开发者 https://www.devze.com 2023-03-22 10:04 出处:网络
Using: Ubuntu 11.04 Django 1.3 Python 2.7 Following the tutorial at Writing your first Django app, part 1

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 na开发者_如何学JAVAme '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


You can use this one: Go through the link Django Utils Timezone

from django.utils.timezone you can import is_aware, is_naive, now and can customise based on your requirements:

Timezone-related classes and functions.

This module uses pytz when it's available and fallbacks when it isn't.

from django.utils.timezone import datetime


Try the following:

from datetime import datetime

Then your code should work. datetime is the package name and inside it is the datetime you want to work with.


from datetime import datetime

This is the right way to import datetime in django. This is for Ubuntu 18.04 or higher I have 20.04.

0

精彩评论

暂无评论...
验证码 换一张
取 消