# Generate CSV files for models
import csv
from django.db.models.loading import get_model, get_apps, get_models
from django.db.models import BooleanField
from django.contrib.admin.views.decorators import staff_member_required
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response
from django.template.defaultfilters import yesno
__all__ = ( 'spreadsheet', )
def _field_extractor_function(field):
"""Return a function that extracts a given field from an instance of a model."""
if field.choices:
return (lambda o: getattr(o, 'get_%s_display' % field.name)())
elif isinstance(field, BooleanField):
return (lambda o: yesno(getattr(o, field.name), "Yes,No"))
else:
return (lambda o: str(getattr(o, field.name)))
@staff_member_required
def spreadsheet(request, app_label, model_name):
"""Return a CSV file for this table."""
# Get the fields of the table
model = get_model(app_label, model_name)
if not model:
raise Http404
fields = model._meta.fields
field_funcs = [ _field_extractor_function(f) for f in fields ]
# set the HttpResponse
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s-%s.csv' % (app_label, model_name)
writer = csv.writer(response, quoting=csv.QUOTE_ALL)
# Write the header of the CSV file
writer.writerow([ f.verbose_name for f in fields ])
# Write all rows of the CSV file
for o in model.objects.all():
writer.writerow([ func(o) for func in field_funcs ])
# All done
return response
# The URL for the spreadsheet
#
# urlpatterns += patterns('foo.utils.spreadsheets',
# (r"^spreadsheets/(?P<app_label>\w+)/(?P<model_name>\w+)/$", "spreadsheet"), # Return a CSV file for this model
# )
Comments
Works beautifully. For unicode support add following code (straight from the docs) on top:
and change line 36 to:
#