Add export data into CSV files action in Django Admin


Having “export data as CSV” action in Django Admin sometimes it useful to exchange data into another platform like Excel. To make this feature, we need to create action in Django admin.

1. Create admin export csv action
Create “action.py” in your app. Then, in this files, we create function to do queryset and export data into CSV files.

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
import csv
from django.http import HttpResponse
from datetime import datetime

def export_to_csv(modeladmin, request, queryset):
    """Exporting queryset results and filter into CSV"""
    # limit only staff and super_user accounts
    if request.user.is_staff or request.user.is_superuser:
        if queryset.count() > 0:
            # generate response and filename
            response = HttpResponse(mimetype="text/csv")
            today = datetime.now().strftime("%Y-%M-%d_%H:%M:%S")
            filename = "records-%s.csv" % today
            response["Content-Disposition"] = (‘attachment; filename="%s"’ %
                                               filename)
            writer = csv.writer(response)

            # Get column name
            columns = [field.name for field in queryset[0]._meta.fields]
            writer.writerow(columns)

            # Write data
            for obj in queryset:
                fields = map(lambda x: generate_value(obj, x), columns)
                writer.writerow(fields)

            return response

export_to_csv.short_description = "Export results to CSV"


def generate_value(obj, column):
    """Get fields value and convert to ASCIC for string type"""
    row = getattr(obj, column)
    if isinstance(row, basestring):
        row = row.encode(‘ascii’, ‘ignore’)
    return row

This script will export “selected data” into CSV.

2. Add actions into admin

1
2
3
class InsuranceAdmin(admin.ModelAdmin):
    ….
    actions = [export_to_csv]

Now, when you go to this pages, you will see “export to csv” option on bottom left menu. Make sure you select the record before click on this menu.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.