Skip to content

Instantly share code, notes, and snippets.

@igniteflow
Created July 10, 2012 12:48
Show Gist options
  • Save igniteflow/3083052 to your computer and use it in GitHub Desktop.
Save igniteflow/3083052 to your computer and use it in GitHub Desktop.
Add an 'Export as csv' admin action to your Django model admin page
import csv
from django.http import HttpResponse
# also include UnicodeWriter from the Python docs http://docs.python.org/library/csv.html
class ExportModel(object):
@staticmethod
def as_csv(meta):
"""
:param meta: (dict) keys should be
'file' (string: absolute path),
'queryset' a Django QuerySet instance,
'fields' a list or tuple of field model field names (strings)
meta = {
'file': '/tmp/products.csv',
'class': Product,
'fields': ('name',)
}
:returns (string) path to file
"""
with open(meta['file'], 'w+') as f:
writer = UnicodeWriter(f, encoding='utf-8')
writer.writerow( meta['fields'] )
for obj in meta['queryset']:
row = [unicode(getattr(obj, field)) for field in meta['fields']]
writer.writerow(row)
path = f.name
return path
def get_model_as_csv_file_response(meta, content_type):
"""
Call this function from your model admin
"""
with open(ExportModel.as_csv(meta), 'r') as f:
response = HttpResponse(f.read(), content_type=content_type)
response['Content-Disposition'] = 'attachment; filename=%s' % f.name.split('/')[-1:][0]
return response
"""
...and then in your app's admin.py
"""
from django.contrib import admin
from myapp import models
def export_products(self, request, queryset):
meta = {
'file': '/tmp/products.csv',
'queryset': queryset,
'fields': ('name',)
}
return get_model_as_csv_file_response(meta, content_type='text/csv')
export_products.short_description = 'Export as csv'
class ProductAdmin(admin.ModelAdmin):
actions = [export_products]
admin.site.register(models.Product, ProductAdmin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment