Login

Generic Outputting CSV with Django

Author:
PatrickPorto
Posted:
January 22, 2016
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

Save the snippet as actions.py within your core app, and then add an action on any model you want in it's ModelAdmin definition.

Example usage:

from actions import export_as_csv_action

class YourModelAdmin(admin.ModelAdmin):
list_display = ('field', 'get_field2')
actions = [export_to_csv(filename='your-model')]
def get_field2(self, obj):
return obj.field2

 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
from django.db.models.fields import FieldDoesNotExist
from django.http import HttpResponse
import unicodecsv as csv


def export_to_csv(description='Export selected objects as CSV file', filename='somefilename', fields=None, header=True):
    def action(modeladmin, request, queryset):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="{filename}.csv"'.format(
            filename=filename,
        )
        list_display = fields or modeladmin.get_list_display(request)
        model = modeladmin.model
        lookup_opts = model._meta
        writer = csv.writer(response, encoding='utf-8')
        if header:
            row = []
            for field_name in list_display:
                try:
                    field = lookup_opts.get_field(field_name)
                    row.append(field.name)
                except FieldDoesNotExist:
                    if hasattr(modeladmin, field_name):
                        method = getattr(modeladmin, field_name)
                    else:
                        method = getattr(model, field_name)
                    row.append(getattr(method, 'short_description', None))
            writer.writerow(row)
        for user in queryset.all():
            row = []
            for field_name in list_display:
                try:
                    row.append(getattr(user, field_name))
                except AttributeError:
                    if hasattr(modeladmin, field_name):
                        method = getattr(modeladmin, field_name)
                    else:
                        method = getattr(model, field_name)
                    row.append(method(user))
            writer.writerow(row)
        return response
    action.short_description = description
    return action

More like this

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

Comments

Please login first before commenting.