ec0479e182591027a9178a07aa161924d30c6c7d
[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
7 try:
8     unicode
9 except NameError:
10     pass
11 else:
12     str = unicode
13
14
15 def export_as_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True):
16     """
17     This function returns an export csv action
18     'fields' and 'exclude' work like in django ModelForm
19     'header' is whether or not to output the column names as the first row
20     """
21     def export_as_csv(modeladmin, request, queryset):
22         """
23         Generic csv export admin action.
24         based on http://djangosnippets.org/snippets/1697/
25         """
26         opts = modeladmin.model._meta
27         field_names = [field.name for field in opts.fields]
28
29         if fields:
30             for f in fields:
31                 if f not in field_names:
32                     field_names.append(f)
33
34         elif exclude:
35             field_names = [f for f in field_names if f not in exclude]
36
37         response = HttpResponse(content_type='text/csv')
38         response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_')
39
40         writer = csv.writer(response)
41
42         if header:
43             writer.writerow(field_names)
44         for obj in queryset:
45             writer.writerow([str(getattr(obj, field)) for field in field_names])
46
47         return response
48
49     export_as_csv.short_description = description
50     return export_as_csv
51