2012-07-12 04:38:39 +00:00
|
|
|
import csv
|
|
|
|
|
|
|
|
from django.http import HttpResponse
|
2015-06-26 03:46:09 +00:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2012-07-12 04:38:39 +00:00
|
|
|
|
|
|
|
|
2015-06-26 03:46:09 +00:00
|
|
|
def export_as_csv_action(description=None, fields=None, exclude=None,
|
|
|
|
header=True):
|
2012-07-12 04:38:39 +00:00
|
|
|
"""
|
|
|
|
This function returns an export csv action
|
2013-06-11 17:10:29 +00:00
|
|
|
'fields' and 'exclude' work like in Django ModelForm
|
2012-07-12 04:38:39 +00:00
|
|
|
'header' is whether or not to output the column names as the first row
|
|
|
|
"""
|
|
|
|
def export_as_csv(modeladmin, request, queryset):
|
|
|
|
"""
|
|
|
|
Generic csv export admin action.
|
|
|
|
based on http://djangosnippets.org/snippets/1697/
|
|
|
|
"""
|
|
|
|
opts = modeladmin.model._meta
|
|
|
|
if fields:
|
|
|
|
fieldset = set(fields)
|
|
|
|
field_names = fieldset
|
|
|
|
elif exclude:
|
|
|
|
excludeset = set(exclude)
|
|
|
|
field_names = field_names - excludeset
|
2014-01-15 14:05:08 +00:00
|
|
|
response = HttpResponse(content_type="text/csv")
|
2017-04-17 12:51:48 +00:00
|
|
|
response["Content-Disposition"] = "attachment; filename=%s.csv" % str(opts).replace(".", "_")
|
2012-07-12 04:38:39 +00:00
|
|
|
writer = csv.writer(response)
|
|
|
|
if header:
|
|
|
|
writer.writerow(list(field_names))
|
|
|
|
for obj in queryset:
|
2014-07-30 18:19:26 +00:00
|
|
|
writer.writerow(
|
2017-04-17 12:51:48 +00:00
|
|
|
[str(getattr(obj, field)).encode("utf-8", "replace") for field in field_names])
|
2012-07-12 04:38:39 +00:00
|
|
|
return response
|
2015-06-26 03:46:09 +00:00
|
|
|
if description is None:
|
|
|
|
description = _("Export selected objects as CSV file")
|
2012-07-12 04:38:39 +00:00
|
|
|
export_as_csv.short_description = description
|
|
|
|
return export_as_csv
|