Skip to content

Instantly share code, notes, and snippets.



Forked from mgerring/
Created Sep 9, 2017
What would you like to do?
"Export to CSV" action for django admin
import unicodecsv
from django.http import HttpResponse
def export_as_csv_action(description="Export selected objects as CSV file",
fields=None, exclude=None, header=True):
This function returns an export csv action
'fields' and 'exclude' work like in django ModelForm
'header' is whether or not to output the column names as the first row
def export_as_csv(modeladmin, request, queryset):
opts = modeladmin.model._meta
if not fields:
field_names = [ for field in opts.fields]
field_names = fields
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_')
writer = unicodecsv.writer(response, encoding='utf-8')
if header:
for obj in queryset:
row = [getattr(obj, field)() if callable(getattr(obj, field)) else getattr(obj, field) for field in field_names]
return response
export_as_csv.short_description = description
return export_as_csv
from django.contrib import admin
from import Location
from django.http import HttpResponse, HttpResponseForbidden
from actions import export_as_csv_action
class SpamAdmin(admin.ModelAdmin):
list_display = ['wink','nudge']
actions = [export_as_csv_action("CSV Export", fields=['wink','nudge'])], LocationAdmin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment