Generic CSV export admin action factory with 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
import csv
from django.http import HttpResponse


def export_select_fields_csv_action(description="Export selected objects as CSV file",
                         fields=None, exclude=None, header=True):
    """
    This function returns an export csv action

    'fields' is a list of tuples denoting the field and label to be exported. Labels
    make up the header row of the exported file if header=True.

        fields=[
                ('field1', 'label1'),
                ('field2', 'label2'),
                ('field3', 'label3'),
            ]

    'exclude' is a flat list of fields to exclude. If 'exclude' is passed,
    'fields' will not be used. Either use 'fields' or 'exclude.'

        exclude=['field1', 'field2', field3]

    'header' is whether or not to output the column names as the first row

    Based on: http://djangosnippets.org/snippets/2020/
    """
    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 = [field.name for field in opts.fields]
        labels = []
        if exclude:
            field_names = [v for v in field_names if v not in exclude]
        elif fields:
            field_names = [k for k, v in fields if k in field_names]
            labels = [v for k, v in fields if k in field_names]

        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_')

        writer = csv.writer(response)
        if header:
            if labels:
                writer.writerow(labels)
            else:
                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


## Usage

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

admin.site.register(ExampleMode, ExampleModelAdmin)

More like this

  1. Generic CSV export admin action factory with relationship spanning fields and labels by blackrobot 1 year, 4 months ago
  2. Admin action for a generic "CSV Export" by javinievas 3 years, 2 months ago
  3. Generic CSV export admin action factory with relationship spanning fields and labels, and many to many fields by selimnairb 2 months, 3 weeks ago
  4. More generic CSV export admin action factory by Rmatt 10 months ago
  5. Ultimate(?) export/download CSV admin action by anentropic 6 months, 3 weeks ago

Comments

shafiquejamal (on May 7, 2013):

Thanks for this - it works well! It is possible to export properties that are defined in the model? For example suppose my model has the following property:

@property def package_value(self): total_value = 0; ... return total_value

If I add the to the tuple ('package_value', 'package_value'), it doesn't show up in the csv. Would you know how I could get this into the CSV? Thanks!

#

(Forgotten your password?)