1

公開日の日時フィールドを持つ 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 を使用) は公開日から 1 か月または 1 年前になります。

{% 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>

私が間違っていることの手がかりはありますか?

4

1 に答える 1