close forgot it?
close
Login with password or OpenID

Export to CSV with Django

The past week as a sub-project of django-conference, I’ve built a really simple and hopefully useful application to make csv exporting extremely easy.

It uses python’s csv library, and can be set up for example with the following code in your urlconf:

from export_csv.views import export_csv 

export_attendees = {
    'queryset': Attendee.objects.all(),
    'filter_by': 'conference__pk',
    'export_data': {'is_presenter': 'Presents',
        'user.get_full_name': 'Attendee',
        'conference': 'Conference',
        'user.get_profile.affiliation': 'Affiliation',
        },
    'require_permission': 'conference.delete_attendee',
}

urlpatterns = patterns('',
    url(r'^export/attendees/(?P<object_id>\d+)/$', export_csv, 
    export_attendees, name='export_attendees'),
)

This code was taken from an ongoing project to build a conference administering application for django (and for the Hungarian Economists Association).

Basically, the above setting will take a queryset by default that can be further filtered to get the data to be exported, and the export_data dictionary describes the columns to be exported. As the example shows, the columns can be either callable or simple properties, and will be evaluated from the instances of the exported queryset, like attendee_instance.is_presenter(). While column headers are given as the values for export_data.

The view code is really simple, the only tricky part was to construct the callable/non-callable object paths described in export_data, this is done by the following method

def get_attr(object, attrs=None):
    if attrs == None or attrs == []:
        return object
    current = attrs.pop(0)
    try:
        return get_attr(callable(getattr(object, current)) and 
                    getattr(object, current)() or 
                    getattr(object, current), attrs)
    except ObjectDoesNotExist:
        return not_available

If you would like to add some extra functionality, like date based exporting, or just would like to play with the code, go and grab it from launchpad:

Add post to: Delicious Reddit Slashdot Digg Technorati Google
Subscribe via RSS | Comment

Previous posts