[Answered ]-Django – non-consecutive months

1👍

Change

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

to

 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]

and then

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

to

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

This should do what you need.

1👍

Hey heey Aidas, thanks a lot. I need to read up more on Python lists. Your answer was it.

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 ''

Note the reversing of the items in the list.

For the template:

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

And the output has both years and months reversed. Perfect!

Leave a comment