Login

Generate a CSV file for a model

Author:
mssnlayam
Posted:
March 30, 2007
Language:
Python
Version:
.96
Score:
7 (after 7 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

luckystarr (on September 11, 2007):

Works beautifully. For unicode support add following code (straight from the docs) on top:

class UnicodeWriter:
    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        self.writer = csv.writer(f, dialect=dialect, **kwds)
        self.encoding = encoding

    def writerow(self, row):         
        self.writer.writerow([s.encode("utf-8") for s in row])

def writerows(self, rows):
    for row in rows:
        self.writerow(row)

and change line 36 to:

writer = UnicodeWriter(response, quoting=csv.QUOTE_ALL)

#

Please login first before commenting.