Last active
June 2, 2019 21:30
-
-
Save bryanchow/1411467 to your computer and use it in GitHub Desktop.
Django Export CSV admin action factory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Django Export CSV admin action factory | |
# https://gist.github.com/1411467 | |
# | |
# Based on http://djangosnippets.org/snippets/2020/ | |
# and http://djangosnippets.org/snippets/1697/ | |
# | |
# Example usage: | |
# | |
# class MyUserAdmin(admin.ModelAdmin): | |
# actions = ( | |
# export_csv_action( | |
# description = "Export CSV", | |
# fields = ('username', 'email',), | |
# header = True, | |
# labels = { | |
# 'username': "User", | |
# 'email': "Email", | |
# }, | |
# filename = "users.csv", | |
# ), | |
# ) | |
try: | |
import unicodecsv as csv | |
except ImportError: | |
import csv | |
from django.http import HttpResponse | |
def export_csv_action(description="Export CSV", | |
fields=None, | |
exclude=None, | |
header=True, | |
labels={}, | |
encoding="utf8", | |
render_null=False, | |
filename=None): | |
""" | |
Returns an admin action that exports the selected objects in CSV format. | |
description: A string describing this admin action | |
fields: A tuple or list of field names to include in the export | |
exclude: A tuple or list of field names to exclude from the export | |
header: A boolean indicating whether a header row should be included | |
filename: The filename of the generated CSV report | |
""" | |
def export_csv(modeladmin, request, queryset): | |
""" | |
Generic CSV export admin action. | |
""" | |
opts = modeladmin.model._meta | |
if filename: | |
csvfilename = filename | |
else: | |
csvfilename = '%s.csv' % unicode(opts).replace('.', '_') | |
if fields: | |
field_names = fields | |
elif exclude: | |
field_names = ( | |
set([field.name for field in opts.fields]) - set(exclude) | |
) | |
response = HttpResponse(content_type="text/csv") | |
response['Content-Disposition'] = ( | |
"attachment; filename=%s" % csvfilename | |
) | |
writer = csv.writer(response, encoding=encoding) | |
if header: | |
header_row = [] | |
for name in field_names: | |
if labels.has_key(name): | |
header_row.append(labels[name]) | |
else: | |
try: | |
field = getattr(modeladmin.model, name) | |
if hasattr(field, 'short_description'): | |
header_row.append(field.short_description) | |
else: | |
header_row.append(name) | |
except AttributeError: | |
header_row.append(name) | |
writer.writerow(header_row) | |
for obj in queryset: | |
row = [] | |
for field in field_names: | |
value = getattr(obj, field) | |
if callable(value): | |
value = value() | |
elif not render_null: | |
value = "" if value is None else value | |
row.append(unicode(value).encode(encoding)) | |
writer.writerow(row) | |
return response | |
export_csv.short_description = description | |
return export_csv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment