Login

Generic CSV export admin action factory with labels

Author:
losttrekker
Posted:
March 9, 2012
Language:
Python
Version:
1.3
Score:
2 (after 2 ratings)

Based on #2020

This snippet creates a simple generic export to csv action that you can specify the fields you want exported and the labels used in the header row for each field. It expands on #2020 by using list comprehensions instead of sets so that you also control the order of the fields as well.

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

#

Please login first before commenting.