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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
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?
#
ARGH... i make mistake...
I passed "month year" instead of "month year"
Sorry.
#
Very useful start to my calendar. Thanks!
#
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?
#
Please login first before commenting.