Login

Generic CSV export admin action factory

Author:
anentropic
Posted:
May 14, 2010
Language:
Python
Version:
1.1
Score:
2 (after 2 ratings)

I've since made a better snippet for this: #2995

based on #1697

This one is even more generic since you can specify which fields to include or exclude, a custom description text for the drop-down menu and whether to output the header row.

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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<br /> I don't see that fix is necessary?

#

anentropic (on January 17, 2012):

@nukeador<br /> 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?

#

Please login first before commenting.