Python Calendar wrapper template tag

 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

  1. Sort Table Headers by insin 6 years, 9 months ago
  2. Group sequence into rows and columns for a TABLE by davidwtbuxton 3 years, 2 months ago
  3. Yet another SQL debugging facility by miracle2k 6 years, 8 months ago
  4. Functional Filters by waterson 6 years, 7 months ago
  5. grouper tag by visgean 2 years, 8 months ago

Comments

lablinux (on June 24, 2009):

I have a problem.

[...] ValueError: month must be in 1..12 [...]

I test this

return '%d - &d' %(int(self.year.resolve(context)), int(self.month.resolve(context)))

and in my view i see:

6 - 2009

Where is my problem?

#

lablinux (on June 24, 2009):

ARGH... i make mistake...

I passed "month year" instead of "month year"

Sorry.

#

xhenxhe (on January 13, 2010):

Very useful start to my calendar. Thanks!

#

venkateshkumar (on December 18, 2013):

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

Invalid block tag: 'get_calendar'

am sure i am doing something wrong here, may i know what is wrong?

#

(Forgotten your password?)