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