1
我有一個Django模型(db是PostgreSQL的)有時間字段出版日期:Django的模板標籤從錯誤的日期顯示爲對象
class Story(models.Model):
...
pub_date = models.DateTimeField(default=datetime.datetime.now)
...
和模板標籤來獲得這些對象給定月份和同期:
from django import template
from news.models import Story
class StoryYearListNode(template.Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
context[self.varname] = Story.live.dates("pub_date", "year").reverse()
return ''
def do_get_story_year_list(parser, token):
"""
Gets a list of years in which stories are published.
Syntax::
{% get_story_year_list as [varname] %}
Example::
{% get_story_year_list as year_list %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError, "'%s' tag takes two arguements" % bits[0]
if bits[1] != "as":
raise template.TemplateSyntaxError, "First arguement to '%s' tag must be 'as'" % bits[0]
return StoryYearListNode(bits[2])
class StoryMonthListNode(template.Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
context[self.varname] = Story.live.dates("pub_date", "month").reverse()
return ''
def do_get_story_month_list(parser, token):
"""
Gets a list of months in which stories are published.
Syntax::
{% get_story_month_list as [varname] %}
Example::
{% get_story_month_list as month_list %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError, "'%s' tag takes two arguements" % bits[0]
if bits[1] != "as":
raise template.TemplateSyntaxError, "First arguement to '%s' tag must be 'as'" % bits[0]
return StoryMonthListNode(bits[2])
register = template.Library()
register.tag('get_story_month_list', do_get_story_month_list)
register.tag('get_story_year_list', do_get_story_year_list)
但是當我使用該標籤的模板,日期(使用get_story_month_list爲例)是一個月或一年從酒吧可以追溯到:
{% load date%}
{% get_story_month_list as month_list %}
<ul class="list-unstyled">
{% for month in month_list %}
<li><a href="{{ month|date:"Y/M"|lower }}/">{{ month|date:"F Y" }}</a></li>
{% endfor %}
</ul>
任何線索我做錯了什麼?
我不認爲它與你的問題有關,但'DateTimeField'具有內置屬性,可通過'auto_now_add'將其設置爲「now」。看到這個問題:http://stackoverflow.com/questions/2771676/django-default-datetime-now-problem – Vincent
是的,我不認爲這與我的問題有關,但我很欣賞信息和鏈接! –
所以它看起來好像這是一個時區問題(相關:http://stackoverflow.com/questions/11174225/error-with-rendering-datetime-object-in-django-templates)。我可以通過關閉設置中的時區來解決問題,但理想情況下,我希望保留此設置。這裏的任何幫助都會很棒。 –