Admin Download as CSV File

 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
import csv
from django.http import HttpResponse
from django.core.exceptions import PermissionDenied
from django.contrib.admin.util import label_for_field

def export_as_csv(description="Download selected rows as CSV file",header=True):
    """
    This function returns an export csv action
    This function ONLY downloads the columns shown in the list_display of the admin
    '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/ and /2020/
        """
        # TODO Also create export_as_csv for exporting all columns including list_display
        if not request.user.is_staff:
            raise PermissionDenied
        opts = modeladmin.model._meta
        field_names = modeladmin.list_display
        if 'action_checkbox' in field_names:
            field_names.remove('action_checkbox')

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

        writer = csv.writer(response)
        if header:
            headers = []
            for field_name in list(field_names):
                label = label_for_field(field_name,modeladmin.model,modeladmin)
                if str.islower(label):
                   label = str.title(label)
                headers.append(label)
            writer.writerow(headers)
        for row in queryset:
            values = []
            for field in field_names:
                value = (getattr(row, field))
                if callable(value):
                    try:
                        value = value() or ''
                    except:
                        value = 'Error retrieving value'
                if value is None:
                    value = ''
                values.append(unicode(value).encode('utf-8'))
            writer.writerow(values)
        return response

    export_as_csv.short_description = description
    return export_as_csv

More like this

  1. Generate a CSV file for a model by mssnlayam 7 years ago
  2. Generic CSV export admin action factory with relationship spanning fields and labels, and many to many fields by selimnairb 2 months, 1 week ago
  3. Ultimate(?) export/download CSV admin action by anentropic 6 months, 2 weeks ago
  4. send_file and send_data by danjak 7 years, 1 month ago
  5. export to csv, import from csv by peiwei 10 months ago

Comments

(Forgotten your password?)