Django模板标签显示对象的错误日期

时间:2013-11-20 12:16:18

标签: python django templates datetime templatetag

我有一个Django模型(db是PostgreSQL),其日期时间字段用于发布日期:

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>

有什么迹象表明我做错了什么?

1 个答案:

答案 0 :(得分:1)

auto_now =在django 1.4.1中我没有为我工作,但下面的代码救了我。

from django.utils.timezone import get_current_timezone
from datetime import datetime

class EntryVote(models.Model):
    voted_on = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        self.voted_on = datetime.now().replace(tzinfo=get_current_timezone())
        super(EntryVote, self).save(*args, **kwargs)