Created
December 21, 2012 21:28
-
-
Save blackrobot/4355962 to your computer and use it in GitHub Desktop.
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
from django.contrib import admin | |
from example.admin_actions import export_csv_action | |
class ExampleModelAdmin(admin.ModelAdmin): | |
raw_id_fields = ('field1',) | |
list_display = ('field1', 'field2', 'field3',) | |
actions = [ | |
export_csv_action("Export Sepecial Report", | |
fields=[ | |
('field1', 'label1'), | |
('foreign_key1__foreign_key2__name', 'label2'), | |
('field3', 'label3'), | |
], | |
header=True | |
), | |
] | |
admin.site.register(ExampleMode, ExampleModelAdmin) |
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
import csv | |
from django.http import HttpResponse | |
def prep_field(obj, field): | |
""" Returns the field as a unicode string. If the field is a callable, it | |
attempts to call it first, without arguments. | |
""" | |
if '__' in field: | |
bits = field.split('__') | |
field = bits.pop() | |
for bit in bits: | |
obj = getattr(obj, bit, None) | |
if obj is None: | |
return "" | |
attr = getattr(obj, field) | |
output = attr() if callable(attr) else attr | |
return unicode(output).encode('utf-8') if output else "" | |
def export_csv_action(description="Export as CSV", fields=None, exclude=None, header=True): | |
""" This function returns an export csv action. """ | |
def export_as_csv(modeladmin, request, queryset): | |
""" Generic csv export admin action. | |
Based on http://djangosnippets.org/snippets/2712/ | |
""" | |
opts = modeladmin.model._meta | |
field_names = [field.name for field in opts.fields] | |
labels = [] | |
if exclude: | |
field_names = [f for f in field_names if f not in exclude] | |
elif fields: | |
field_names = [field for field, _ in fields] | |
labels = [label for _, label in fields] | |
response = HttpResponse(mimetype='text/csv') | |
response['Content-Disposition'] = 'attachment; filename=%s.csv' % ( | |
unicode(opts).replace('.', '_') | |
) | |
writer = csv.writer(response) | |
if header: | |
writer.writerow(labels if labels else field_names) | |
for obj in queryset: | |
writer.writerow([prep_field(obj, field) for field in field_names]) | |
return response | |
export_as_csv.short_description = description | |
return export_as_csv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment