Generic csv export admin action

 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. Generic admin action export selected rows to excel by jordic 1 year, 7 months ago
  2. Generic admin action export selected rows to excel by aemb87 7 months ago
  3. Admin action for a generic "CSV Export" by javinievas 2 years, 3 months ago
  4. Generic CSV export admin action factory with relationship spanning fields and labels by blackrobot 5 months ago
  5. Generic CSV export admin action factory with labels by losttrekker 1 year, 2 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?

#

weitlandt (on May 5, 2010):

Combined dek's idea with a snippet from Anatoly Ivanov.

Works, with german ÄÖÜ and TextFields, Excel 2003+ compatible:

http://weitlandt.com/theme/2010/05/wir-djangonauten-csv-export-nach-excel-mit-umlauten/

#

weitlandt (on May 5, 2010):

Combined dek's idea with a snippet from Anatoly Ivanov.

Solved, with german ÄÖÜ and TextFields, Excel 2003+ compatible:

http://weitlandt.com/theme/2010/05/wir-djangonauten-csv-export-nach-excel-mit-umlauten/

#

anentropic (on May 14, 2010):

thanks!

a slightly customised version: #2020

#

(Forgotten your password?)