views:

53

answers:

1

FullCalendar supports taking in a JSON object through AJAX for it's events, this can be done on initialization or later like this:

$('#calendar').fullCalendar('addEventSource', "/{{ user }}/events/" );

The serialization itself in my Django view looks like this:

...
events = Event.objects.filter(user=request.user, start__gte=start, end__lte=end)
message = serializers.serialize("json", events, ensure_ascii=False)
...

The JSON object that gets returned looks like this:

[{"pk": 2, "model": "main.event", "fields": {"url": null, "start": "2010-10-09 08:30:00", "end": "2010-10-09 10:30:00", "user": 1, "title": "sdf"}}, {"pk": 3, "model": "main.event", "fields": {"url": null, "start": "2010-10-03 08:30:00", "end": "2010-10-03 12:00:00", "user": 1, "title": "sdf2"}}]

The Fullcalendar event takes in the following variables: id, title, start, end, allDay and url.

I think FullCalendar is receiving my JSON object right now (not sure how to check) but it's probably not acceptable, how can I make it acceptible for FullCalendar? It probably has too look something like this:

[{id: 1, title: 'Title1', start: new Date(2010, 10, 3, 8, 30), end: new Date(2010, 10, 3, 12, 0), allDay: false, url: false}]

or:

[{"id": 1, "title": 'Title1', "start": new Date(2010, 10, 3, 8, 30), "end": new Date(2010, 10, 3, 12, 0), "allDay": false, "url": false}]

Or even something else, not sure.

So basically the situation is that I haven't worked with JSON objects before and I'm not sure how best to serialize the model into an acceptable JSON object, any ideas?

+1  A: 

Don't use Django's built-in serializers for this. I almost never use them - they are very inflexible.

Luckily, it's very simple to serialize the content yourself.

from django.utils import simplejson
from django.core.serializers.json import DjangoJSONEncoder

events = Event.objects.filter(
              user=request.user, start__gte=start, end__lte=end
         ).values('id', 'title', 'start', 'end')
data = simplejson.dumps(list(events), cls=DjangoJSONEncoder)

Here I'm just getting a dictionary from the queryset via values, and passing it to simplejson to encode the select list of fields. I need to use the DjangoJSONEncoder as by default json doesn't know about datetimes, so this encoder adds that functionality.

Daniel Roseman