mise-en-production
[auf_framonde.git] / project / cmsplugin_contact_plus / actions.py
1 import csv
2 from django.http import HttpResponse
3 #from setuptools.compat import unicode
4
5
6 class LUT(object):
7
8 def __init__(self):
9 self.lut = []
10
11 def add_field(self, field_name):
12 """ """
13 if field_name not in self.lut:
14 self.lut.append(field_name)
15
16 def get_idx(self, field_name):
17 """ """
18 return self.lut.index(field_name)
19
20
21
22 def export_as_csv_action(description="Export selected objects as CSV file",
23 fields=None, exclude=None, header=True, json_fields=None):
24 """
25 This function returns an export csv action
26 'fields' and 'exclude' work like in django ModelForm
27 'header' is whether or not to output the column names as the first row
28
29 json_fields will be exploaded to rows.
30 """
31
32 from itertools import chain
33
34 def export_as_csv(modeladmin, request, queryset):
35 """
36 Generic csv export admin action.
37 based on http://djangosnippets.org/snippets/2369/
38 """
39 opts = modeladmin.model._meta
40 field_names = set([field.name for field in opts.fields])
41 many_to_many_field_names = set([many_to_many_field.name for many_to_many_field in opts.many_to_many])
42 if fields:
43 fieldset = set(fields)
44 field_names = field_names & fieldset
45 elif exclude:
46 excludeset = set(exclude)
47 field_names = field_names - excludeset
48
49 response = HttpResponse(content_type='text/csv')
50 response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_')
51
52 writer = csv.writer(response)
53 """
54 if header:
55 writer.writerow(list(chain(field_names, many_to_many_field_names)))
56 # default: does not split json_fields to rows. (json is in one row)
57 if not json_fields:
58 for obj in queryset:
59 row = []
60 for field in field_names:
61 row.append(unicode(getattr(obj, field)))
62 for field in many_to_many_field_names:
63 row.append(unicode(getattr(obj, field).all()))
64 writer.writerow(row)
65 else:
66 """
67 # build LUT
68 lut = LUT()
69 for obj in queryset:
70 for field in field_names:
71 if field in json_fields:
72 j = getattr(obj, field)
73 for l in j:
74 try:
75 for k, v in l.iteritems():
76 lut.add_field(k)
77 except AttributeError:
78 pass
79 else:
80 lut.add_field(field)
81
82 if header:
83 writer.writerow(lut.lut)
84 for obj in queryset:
85 row = ['']*len(lut.lut)
86 for field in field_names:
87 if field in json_fields:
88 j = getattr(obj, field)
89 for l in j:
90 for k, v in l.iteritems():
91 try:
92 row[lut.get_idx(k)] = v.encode('utf-8')
93 except AttributeError:
94 pass
95 else:
96 row[lut.get_idx(field)] = unicode(getattr(obj, field))
97 for field in many_to_many_field_names:
98 row[lut.get_idx(field)] = unicode(getattr(obj, field).all())
99 writer.writerow(row)
100
101
102 return response
103 export_as_csv.short_description = description
104 return export_as_csv