1 # Source: https://gist.github.com/jeremyjbowers/e8d007446155c12033e6
2 from __future__ import unicode_literals
5 from django.http import HttpResponse
6 from django.utils.translation import ugettext_lazy as _
16 def export_as_csv_action(description=_("Export selected objects as CSV file"), fields=None, exclude=None, header=True):
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
22 def export_as_csv(modeladmin, request, queryset):
24 Generic csv export admin action.
25 based on http://djangosnippets.org/snippets/1697/
27 opts = modeladmin.model._meta
28 field_names = fields or [field.name for field in opts.fields]
31 field_names = [f for f in field_names if f not in exclude]
33 response = HttpResponse(content_type='text/csv')
34 response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_')
36 writer = csv.writer(response)
39 writer.writerow(field_names)
42 for field in field_names:
43 value = getattr(obj, field)
46 row.append(str(value))
51 export_as_csv.short_description = description