Generic CSV export admin action factory

 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
import csv
from django.http import HttpResponse

def export_as_csv_action(description="Export selected objects as CSV file",
                         fields=None, exclude=None, header=True):
    """
    This function returns an export csv action
    'fields' and 'exclude' work like in django ModelForm
    'header' is whether or not to output the column names as the first row
    """
    def export_as_csv(modeladmin, request, queryset):
        """
        Generic csv export admin action.
        based on http://djangosnippets.org/snippets/1697/
        """
        opts = modeladmin.model._meta
        field_names = set([field.name for field in opts.fields])
        if fields:
            fieldset = set(fields)
            field_names = field_names & fieldset
        elif exclude:
            excludeset = set(exclude)
            field_names = field_names - excludeset
        
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_')
        
        writer = csv.writer(response)
        if header:
            writer.writerow(field_names)
        for obj in queryset:
            writer.writerow([unicode(getattr(obj, field)).encode('utf-8') for field in field_names])
        return response
    export_as_csv.short_description = description
    return export_as_csv



# example usage:

class SubscriberAdmin(admin.ModelAdmin):
    raw_id_fields = ('logged_in_as',)
    list_display = ('email', 'date', 'logged_in_as',)
    actions = [export_as_csv_action("Export selected emails as CSV file", fields=['email'], header=False),]

admin.site.register(UpdatesSubscriber, SubscriberAdmin)

More like this

  1. Generic CSV export admin action factory with labels by losttrekker 2 years, 1 month ago
  2. Generic CSV export admin action factory with relationship spanning fields and labels, and many to many fields by selimnairb 2 months, 2 weeks ago
  3. Generic admin action export selected rows to excel by jordic 2 years, 6 months ago
  4. Admin action for a generic "CSV Export" (fix for unicode) by __alexander__ 4 months, 3 weeks ago
  5. Generic CSV export admin action factory with relationship spanning fields and labels by blackrobot 1 year, 4 months ago

Comments

hotchip (on July 20, 2010):

Minor fix

Replace: writer.writerow(field_names) with: writer.writerow(list(field_names))

#

nukeador (on December 7, 2010):

Another fix to support unicode fields:

Replace:

writer.writerow([unicode(getattr(obj, field)) for field in field_names])

To:

writer.writerow([unicode(getattr(obj, field)).encode("utf-8") for field in field_names])

#

smcoll (on December 30, 2010):

How could this be adapted to show values from foreignkeys? For example, in line 44:

fields=['email', 'fkfield__fieldname']

#

anentropic (on January 17, 2012):

@hotchip
I don't see that fix is necessary?

#

anentropic (on January 17, 2012):

@nukeador
good tip, yes seems to need that

#

msaron (on January 24, 2012):

@hotchip Thanks for that fix. The action did not work without your modification.

#

leandro.abilio (on August 1, 2012):

Is there anyway to export a field from the last row of an Inline class?

#

(Forgotten your password?)