Nov

27

These Are the Months Of Our Lives

Behold! An update!

I've just added month-based archiving. It's just another wrapper around a generic view. I did write a couple template tags to help build my list of archive links the way I wanted to. I wanted to present a flat list of months with posts in them, leaving out the year-archive pages entirely.

Here's the template code I wrote to present the list of archive month links on the home page:

<ul class="nav-bar">
<li>Archive: </li>
{% for d in date_list|months_with_content %}
{% with d|date:"F" as m %}
<li><a href="{% url blog_archive_month year=d.year,month=m.lower %}">{{ m }} {{ d.year }}</a></li>
{% endwith %}
{% endfor %}
</ul>

For the month archive template I wrote a different block of code to link to list the current month and the months on either side, since that's what the archive_month view affords me

<ul class="nav-bar">
<li>Archive: </li>
 
{% if previous_month|has_posts_in_month %}
{% with previous_month|date:"F" as month_str %}
<li><a href="{% url blog_archive_month year=previous_month.year,month=month_str.lower %}">{{ month_str }} {{ previous_month.year }}</a></li>
{% endwith %}
{% endif %}
 
{% with month|date:"F" as month_str %}
<li><a class="active" href="{% url blog_archive_month year=month.year,month=month_str.lower %}">{{ month_str }} {{ month.year }}</a></li>
{% endwith %}
 
{% if next_month|has_posts_in_month %}
{% with next_month|date:"F" as month_str %}
<li><a href="{% url blog_archive_month year=next_month.year,month=month_str.lower %}">{{ month_str }} {{ next_month.year }}</a></li>
{% endwith %}
{% endif %}
</ul>

And finally, here are the two template tags I wrote that are used in that template code:

@register.filter
def months_with_content(date_list):
"""
Returns a list of months where there are blog posts within the year range
provided.
 
Syntax:
 
{{ date_list|months_with_content }}
 
"""
dates = []
for year_date in date_list:
dates += list(BlogPost.objects.filter(pub_dateyear=year_date.year).dates('pub_date', 'month'))
return dates
 

@register.filter
def has_posts_in_month(date):
if not date:
return False
return BlogPost.objects.filter(pub_date
year=date.year, pub_date__month=date.month).count() > 0

Can you tell I'm a back-end programmer from that beastly Django templating?