Admin action for a generic "CSV Export" (fix for unicode)

 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
import csv
from unidecode import unidecode

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/2369/
        """
        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(list(field_names))
        for obj in queryset:
            writer.writerow([unidecode(unicode(getattr(obj, field))) for field in field_names])
        return response
    export_as_csv.short_description = description
    return export_as_csv

More like this

  1. Admin action for a generic "CSV Export" by javinievas 3 years, 2 months ago
  2. Generic admin action export selected rows to excel by jordic 2 years, 6 months ago
  3. Django Admin CSV Export Mixin by Ceran 1 year ago
  4. Generic admin action to export data into excel/csv by vinay.chittora 8 months, 3 weeks ago
  5. Generic CSV Export by zbyte64 5 years, 10 months ago

Comments

(Forgotten your password?)