This code generates a CSV file for a model. The URL is http://example.com/spreadsheets/app_label/model_name/ (replace spreadsheets for admin, from the URL for the model's admin page.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | # 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
# )
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Works beautifully. For unicode support add following code (straight from the docs) on top:
and change line 36 to:
#
Please login first before commenting.