gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:05 25 4
gpt4 key购买 nike

我有一个 Django 模型(数据库是 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>

知道我做错了什么吗?

最佳答案

auto_now=True 在 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)

关于python - Django 模板标签显示对象的错误日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20095753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com