-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactions.py
26 lines (22 loc) · 908 Bytes
/
actions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import csv
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.utils.encoding import smart_str, smart_unicode
def export_as_csv(modeladmin, request, queryset):
"""
Generic csv export admin action.
"""
if not request.user.is_staff:
raise PermissionDenied
opts = modeladmin.model._meta
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_')
writer = csv.writer(response)
field_names = [field.name for field in opts.fields]
# Write a first row with header information
writer.writerow(field_names)
# Write data rows
for obj in queryset:
writer.writerow([smart_str(getattr(obj, field)) for field in field_names])
return response
export_as_csv.short_description = "Export selected objects as csv file"