Fix for CSV export.
[fnpdjango.git] / fnpdjango / actions.py
1 # Source: https://gist.github.com/jeremyjbowers/e8d007446155c12033e6
2 from __future__ import unicode_literals
3
4 import csv
5 from django.http import HttpResponse
6 from django.utils.translation import ugettext_lazy as _
7
8 try:
9     unicode
10 except NameError:
11     pass
12 else:
13     str = unicode
14
15
16 def export_as_csv_action(description=_("Export selected objects as CSV file"), fields=None, exclude=None, header=True):
17     """
18     This function returns an export csv action
19     'fields' and 'exclude' work like in django ModelForm
20     'header' is whether or not to output the column names as the first row
21     """
22     def export_as_csv(modeladmin, request, queryset):
23         """
24         Generic csv export admin action.
25         based on http://djangosnippets.org/snippets/1697/
26         """
27         opts = modeladmin.model._meta
28         field_names = fields or [field.name for field in opts.fields]
29
30         if exclude:
31             field_names = [f for f in field_names if f not in exclude]
32
33         response = HttpResponse(content_type='text/csv')
34         response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_')
35
36         writer = csv.writer(response)
37
38         if header:
39             writer.writerow(field_names)
40         for obj in queryset:
41             row = []
42             for field in field_names:
43                 value = getattr(obj, field)
44                 if callable(value):
45                     value = value()
46                 row.append(str(value))
47             writer.writerow(row)
48
49         return response
50
51     export_as_csv.short_description = description
52     return export_as_csv
53