English 中文(简体)
Django-非连续月份
原标题:Django - non-consecutive months

我想在我的博客旁边列出一个列表,显示只有条目的年份和月份,如下所示:

2011 - Jan, Feb
2010 - Jan, Mar, May, Jun, Jul, Aug, Oct, Nov, Dec
2009 - Sep, Oct, Nov, Dec

我已经制作了自定义模板标记,这样我就可以将其放置到base.html中。

目前,它生成的列表如下所示:

2011 - 1, 2
2010 - 1, 3, 5, 6, 7, 8, 10, 11, 12
2009 - 9, 10, 11, 12

我已经构建了一个自定义模板标记,它是(感谢阿拉斯代尔cig212):

from django import template
from blog.models import Post

register = template.Library()

class PostList(template.Node):
def __init__(self, var_name):
    self.var_name = var_name

def render(self, context):
    my_months = [ Jan ,  Feb ,  Mar ,  Apr ,  May ,  Jun , 
        Jul ,  Aug ,  Sept ,  Oct ,  Nov ,  Dec ]

       arch = Post.objects.dates( publish ,  month , order= DESC )

       archives = {}
       for i in arch:
         year = i.year
         month = i.month
         if year not in archives: 
             archives[year] = [] 
             archives[year].append(month) 
         else: 
             if month not in archives[year]: 
                 archives[year].append(month)

    context[self.var_name] = archives.items()
    return   


@register.tag
def get_post_list(parser, token):
    """
    Generates a list of months that blog posts exist.
    Much like the  year  archive.

    Syntax::

      {% get_post_list as [var_name] %}

    Example usage::

      {% get_post_list as posts_list %}
      (This  var_name  is the one inserted into the Node)

    """
    try:
       tag_name, arg = token.contents.split(None, 1)
    except ValueError:
       raise template.TemplateSyntaxError, "%s tag requires arguments" % token.contents.split()[0]
    m = re.search(r as (w+) , arg)
    if not m:
        raise template.TemplateSyntaxError, "%s tag had invalid arguments" % tag_name
    var_name = m.groups()[0]
    return PostListNode(var_name)

模板如下所示:

{% load blog %}
{% get_post_list as posts_list %}
{% for years, months in posts_list %} 
    {{ years }} 
    {% for month in months %} 
    <a href="{{ years }}/{{ month }}">{{ month }}</a> 
    {% endfor %} 
    <br /> 
{% endfor %}

那么,我如何将自定义标记中的my_months标签添加到标记生成的月份编号上呢。我知道我需要在自定义标记中使用enumerate(),但我迷失了方向。

最佳回答

改变

 if year not in archives: 
     archives[year] = [] 
     archives[year].append(month) 
 else: 
     if month not in archives[year]: 
         archives[year].append(month)

 if year not in archives: 
     archives[year] = {} 
     archives[year][month] = my_months[month - 1]
 else: 
     if month not in archives[year]: 
         archives[year][month] = my_months[month - 1]

然后

{% for years, months in posts_list %} 
    {{ years }} 
    {% for month in months %} 
    <a href="{{ years }}/{{ month }}">{{ month }}</a> 
    {% endfor %} 
    <br /> 
{% endfor %}

{% for years, months in posts_list %} 
    {{ years }} 
    {% for month_number, month_name in months.items %} 
    <a href="{{ years }}/{{ month_number }}">{{ month_name }}</a> 
    {% endfor %} 
    <br /> 
{% endfor %}

这应该能满足你的需求。

问题回答

嗨,嗨,艾达斯,非常感谢。我需要阅读更多关于Python列表的内容。你的答案是肯定的。

Here is the code I finally used. For the custom tag:

class PostList(template.Node):
def __init__(self, var_name):
    self.var_name = var_name

def render(self, context):
    my_months = [ Jan ,  Feb ,  Mar ,  Apr ,  May ,  Jun , 
        Jul ,  Aug ,  Sept ,  Oct ,  Nov ,  Dec ]

    arch = Post.objects.dates( publish ,  month , order= DESC )

    archives = {}
    for i in arch:
        year = i.year
        month = i.month
        if year not in archives: 
            archives[year] = {} 
            archives[year][month] = my_months[month - 1]
        else: 
            if month not in archives[year]: 
                archives[year][month] = my_months[month - 1]

    context[self.var_name] = sorted(archives.items(),reverse=True)
    return   

注意列表中项目的颠倒。

对于模板:

{% get_post_list as posts_list %}
{% for years, months in posts_list %} 
     {{ years }} 
     {% for month_number, month_name in months.items %} 
          <li>
             <a href="{{ years }}/{{ month_name|lower }}/">{{ month_name }}</a> 
          </li>
      {% endfor %} 
      <br /> 
{% endfor %}

产量在几年和几个月内都出现了逆转。完美的





相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签