Generate a CSV file for a model

 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. Generic CSV export admin action factory with relationship spanning fields and labels, and many to many fields by selimnairb 2 months, 3 weeks ago
  2. Django Admin CSV Export Mixin by Ceran 1 year ago
  3. Admin Download as CSV File by msaron 2 years, 2 months ago
  4. Generic csv export admin action by dek 4 years, 8 months ago
  5. Non model specific CSV export of database content by sethtrain 6 years, 2 months 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)

#

(Forgotten your password?)