Login

Generic csv export admin action

Author:
dek
Posted:
August 25, 2009
Language:
Python
Version:
1.1
Score:
7 (after 7 ratings)

A generic admin action to export selected objects as csv file. The csv file contains a first line with header information build from the models field names followed by the actual data rows.

Access is limited to staff users.

Requires django-1.1.

Usage:

Add the code to your project, e.g. a file called actions.py in the project root.

Register the action in your apps admin.py:

from myproject.actions import export_as_csv
class MyAdmin(admin.ModelAdmin):
    actions = [export_as_csv]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import csv
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse

def export_as_csv(modeladmin, request, queryset):
    """
    Generic csv export admin action.
    """
    if not request.user.is_staff:
        raise PermissionDenied
    opts = modeladmin.model._meta
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_')
    writer = csv.writer(response)
    field_names = [field.name for field in opts.fields]
    # Write a first row with header information
    writer.writerow(field_names)
    # Write data rows
    for obj in queryset:
        writer.writerow([getattr(obj, field) for field in field_names])
    return response
export_as_csv.short_description = "Export selected objects as csv file"

More like this

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

Comments

gamesbook (on March 28, 2010):

This generates the error "'ascii' codec can't encode characters in position ...". How can this be extended to handle UTF-8 encoding?

#

Please login first before commenting.