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