1 # Source: https://gist.github.com/jeremyjbowers/e8d007446155c12033e6
2 from __future__ import unicode_literals
5 from django.http import HttpResponse
15 def export_as_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True):
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
21 def export_as_csv(modeladmin, request, queryset):
23 Generic csv export admin action.
24 based on http://djangosnippets.org/snippets/1697/
26 opts = modeladmin.model._meta
27 field_names = [field.name for field in opts.fields]
31 if f not in field_names:
35 field_names = [f for f in field_names if f not in exclude]
37 response = HttpResponse(content_type='text/csv')
38 response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_')
40 writer = csv.writer(response)
43 writer.writerow(field_names)
45 writer.writerow([str(getattr(obj, field)) for field in field_names])
49 export_as_csv.short_description = description