Class Based View MySQL DateTimeField received a naive datetime

给你一囗甜甜゛ 提交于 2019-12-11 01:48:31

问题


I am very new to Django and at the end of my rope and really need some help.

I do not know how to use a "class based view" and change the incoming datetimefield from my MySQL database into a Time Zone Supported entry that it seems to need. The database stores it in UTC and my system is on PST.

I am getting this error:

DateTimeField received a naive datetime (2012-09-01 00:00:00) while time zone support is active

On my MonthArchiveView, DayArchiveView, DateDetailView 's only. For some reason my ArchiveIndexView, YearArchiveView class based views work ok.

Here is my model:

class blogpost(models.Model):
  blog_title = models.CharField(max_length=200)
  blog_slug = models.SlugField(unique_for_date='blog_pub_date', max_length=200)
  blog_content = models.TextField()
  blog_pub_date = models.DateTimeField(default=datetime.now())
  blog_category = models.ForeignKey('blogcategory')

Here is one of my Views:

class ThoughtsDetailView(DateDetailView):
  template_name='thoughts/thoughts_detail.html'
  queryset = blogpost.objects.all()
  date_field = 'blog_pub_date'
  slug_field = 'blog_slug'
  context_object_name = 'thoughts_detail'
  month_format = '%m'
  allow_future = 'true'

Here is an example template:

{% block content-inner-left %}
<h1>{{ thoughts_detail.blog_title }}</h1>
<div id="blogpost">
  <p class="blogsmalldate">[ Posted on {{ thoughts_detail.blog_pub_date|date:"l, F dS, Y" }}, {{ thoughts_detail.blog_pub_time|date:"g:i a" }} ]</p>
  <br />
  <p>{{ thoughts_detail.blog_content|safe|linebreaks }}</p>
</div>
{% endblock content-inner-left %}

Can someone help me understand how to fix my Day Detail View so that it stays as a Class Based View and then I can probably figure out the others. I even tried to use PYTZ but don't understand enough how to change the class based view to use it. Thank you....


回答1:


The problem is not in the view, but in the fact that the dates are stored in the database without a timezone information, while Django is set up to support timezones. If you don't need timezone support, simply set USE_TZ = False in the settings.py; if you do, make sure that the database stores the dates with the timezone information. More details on that can be found at https://docs.djangoproject.com/en/1.4/topics/i18n/timezones/#naive-and-aware-datetime-objects



来源:https://stackoverflow.com/questions/12701460/class-based-view-mysql-datetimefield-received-a-naive-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!