Generic CSV export admin action factory with relationship spanning fields and labels

 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import csv
from django.http import HttpResponse
 
 
def prep_field(obj, field):
    """ Returns the field as a unicode string. If the field is a callable, it
    attempts to call it first, without arguments.
    """
    if '__' in field:
        bits = field.split('__')
        field = bits.pop()
 
        for bit in bits:
            obj = getattr(obj, bit, None)
 
            if obj is None:
                return ""
 
    attr = getattr(obj, field)
    output = attr() if callable(attr) else attr
    return unicode(output).encode('utf-8') if output else ""
 
 
def export_csv_action(description="Export as CSV", fields=None, exclude=None, header=True):
    """ This function returns an export csv action. """
    def export_as_csv(modeladmin, request, queryset):
        """ Generic csv export admin action.
        Based on http://djangosnippets.org/snippets/2712/
        """
        opts = modeladmin.model._meta
        field_names = [field.name for field in opts.fields]
        labels = []
 
        if exclude:
            field_names = [f for f in field_names if f not in exclude]
 
        elif fields:
            field_names = [field for field, _ in fields]
            labels = [label for _, label in fields]
 
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename=%s.csv' % (
                unicode(opts).replace('.', '_')
            )
 
        writer = csv.writer(response)
 
        if header:
            writer.writerow(labels if labels else field_names)
 
        for obj in queryset:
            writer.writerow([prep_field(obj, field) for field in field_names])
        return response
    export_as_csv.short_description = description
    return export_as_csv


## Example Usage

from django.contrib import admin

 
class ExampleModelAdmin(admin.ModelAdmin):
    raw_id_fields = ('field1',)
    list_display = ('field1', 'field2', 'field3',)
    actions = [
        export_csv_action("Export Sepecial Report",
            fields=[
                ('field1', 'label1'),
                ('foreign_key1__foreign_key2__name', 'label2'),
                ('field3', 'label3'),
            ],
            header=True
        ),
    ]
 
admin.site.register(ExampleMode, ExampleModelAdmin)

More like this

  1. Generic CSV export admin action factory with labels by losttrekker 1 year, 2 months ago
  2. Generic CSV export admin action factory by anentropic 3 years ago
  3. Admin action for a generic "CSV Export" by javinievas 2 years, 3 months ago
  4. Generic admin action export selected rows to excel by jordic 1 year, 7 months ago
  5. Admin Download as CSV File by msaron 1 year, 3 months ago

Comments

arnocig (on April 26, 2013):

This snippet is very good. Vous pouvez acheter une cigarette electronique sur internet.

#

cigpure (on May 20, 2013):

it's a very good snippet, working very well, good job. veuillez consulter Boutique de cigarette electronique

#

AILS (on May 22, 2013):

Partez en [HTML_REMOVED]s[HTML_REMOVED]jour linguistique [HTML_REMOVED] Malte[HTML_REMOVED] avec AILS séjour linguistique ;)

#

uagainho (on May 23, 2013):

Great snipper, I used it on my site to acheter une cigarette electronique en ligne works great !

#

ecigarette-france (on May 24, 2013):

Fumer sans risque ? Visitez notre boutique cigarette électronique pour obtenir le nécessaire. Optez pour une cigarette electronique eRoll et du e-liquide saveur régulier par exemple en découvrant nos gammes de produits.

#

(Forgotten your password?)