Login

Python Calendar wrapper template tag

Author:
dokterbob
Posted:
May 5, 2009
Language:
Python
Version:
1.0
Tags:
template tag date calendar
Score:
4 (after 4 ratings)

This tag gives you an iterable Python Calendar object in your template namespace. It is used in the django-calendar project.

Use it as follows in your template:

{% get_calendar for <month_number_or_variable> <year_or_variable> as calendar %}
<table>
    <tr>
        <th>Mon</th>
        <th>Tue</th>
        <th>Wed</th>
        <th>Thu</th>
        <th>Fri</th>
        <th>Sat</th>
        <th>Sun</th>        
    </tr>
    {% for week in calendar %}
    <tr>
        {% for day in week %}
        <td>{{ day.day }}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from django import template
 
from calendar import Calendar
import datetime
 
import re
 
register = template.Library()
 
@register.tag(name="get_calendar")
def do_calendar(parser, token):
    syntax_help = "syntax should be \"get_calendar for <month> <year> as <var_name>\""
    # This version uses a regular expression to parse tag contents.
    try:
        # Splitting by None == splitting by spaces.
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires arguments, %s" % (token.contents.split()[0], syntax_help)
    m = re.search(r'for (.*?) (.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError, "%r tag had invalid arguments, %s" % (tag_name, syntax_help)
    
    return GetCalendarNode(*m.groups())
 
class GetCalendarNode(template.Node):
    def __init__(self, month, year, var_name):
        self.year = template.Variable(year)
        self.month = template.Variable(month)
        self.var_name = var_name
        
    def render(self, context):
        mycal = Calendar()
        context[self.var_name] = mycal.monthdatescalendar(int(self.year.resolve(context)), int(self.month.resolve(context)))
        
        return ''

More like this

Comments

lablinux (on June 24, 2009):
<p>I have a problem.</p> <p>[...] ValueError: month must be in 1..12 [...]</p> <p>I test this</p> <p>return '%d - &d' %(int(self.year.resolve(context)), int(self.month.resolve(context)))</p> <p>and in my view i see:</p> <p>6 - 2009</p> <p>Where is my problem?</p>

#

lablinux (on June 24, 2009):
<p>ARGH... i make mistake... </p> <p>I passed "month year" instead of "month year"</p> <p>Sorry.</p>

#

xhenxhe (on January 13, 2010):
<p>Very useful start to my calendar. Thanks!</p>

#

venkateshkumar (on December 18, 2013):
<p>Hi, i am a newbie in django.. I put the above python code in views.py and the template code (html) in html file. I get the error </p> <p>Invalid block tag: 'get_calendar'</p> <p>am sure i am doing something wrong here, may i know what is wrong?</p>

#

Please login first before commenting.