06Oct

Generate Google Calendar templates from Django-Events

Posted by Elf Sternberg as django, python, web development

Hot on the heels of my last entry, the next utility is needed to extend the event object to automatically produce a URL compatible with Google Calendar’s “create an event” handler. Now, I could extend the Event application myself and add a get_google_url() method to the model, but let’s try to do this The Django Way. All I want is a URL, and I need it in specific templates. That says to me: template tag. Even better, template tag filter.

This example is problematic in that we only needed dates, not times. This does need work to extend it to handle times.

Sticking with my convention of naming extensions to existing apps project_app, the filename becomes:

<<project_events_tags.py>>=
from django import template
from django.contrib.sites.models import Site
from django.utils.http import urlquote_plus

register = template.Library()

@register.filter
def google_calendarize(event):
    st = event.start
    en = event.end and event.end or event.start
    tfmt = '%Y%m%dT000000'

    dates = '%s%s%s' % (st.strftime(tfmt), '%2F', en.strftime(tfmt))
    name = urlquote_plus(event.name)

    s = ('http://www.google.com/calendar/event?action=TEMPLATE&' +
         'text=' + name + '&' +
         'dates=' + dates + '&' +
         'sprop=website:' + urlquote_plus(Site.objects.get_current().domain))

    if event.location:
        s = s + '&location=' + urlquote_plus(event.location)

    return s + '&trp=false'

google_calendarize.safe = True

And this is invoked via:

<<events.html>>=
{% load project_events_tags %}
...
<a href="{{ event|google_calendarize }}">+ Add to Google Calendar</a>

It couldn’t be easier.

Comment Form

Subscribe to Feed

Categories

Calendar

October 2010
M T W T F S S
« Sep   Nov »
 123
45678910
11121314151617
18192021222324
25262728293031