from django.conf.urls import patterns, url
from django.http import HttpResponse, Http404
+from edumed.utils import UnicodeCSVWriter
from .forms import contact_forms, admin_list_width
from .models import Contact
contacts_by_spec.setdefault(tuple(keys), []).append(contact)
response = HttpResponse(content_type='text/csv')
- csv_writer = csv.writer(response)
+ csv_writer = UnicodeCSVWriter(response)
# Generate list for each body key set
for keys, contacts in contacts_by_spec.items():
for key in keys:
if key not in record:
record[key] = ''
- csv_writer.writerow([record[key].encode('utf-8') for key in keys])
+ csv_writer.writerow([record[key] for key in keys])
csv_writer.writerow([])
response['Content-Disposition'] = 'attachment; filename="kontakt.csv"'
--- /dev/null
+# -*- coding: utf-8 -*-
+import codecs
+import csv
+
+import cStringIO
+
+
+# source: https://docs.python.org/2/library/csv.html#examples
+class UnicodeCSVWriter(object):
+ """
+ A CSV writer which will write rows to CSV file "f",
+ which is encoded in the given encoding.
+ """
+
+ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
+ # Redirect output to a queue
+ self.queue = cStringIO.StringIO()
+ self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
+ self.stream = f
+ self.encoder = codecs.getincrementalencoder(encoding)()
+
+ def writerow(self, row):
+ self.writer.writerow([s.encode("utf-8") for s in row])
+ # Fetch UTF-8 output from the queue ...
+ data = self.queue.getvalue()
+ data = data.decode("utf-8")
+ # ... and reencode it into the target encoding
+ data = self.encoder.encode(data)
+ # write to the target stream
+ self.stream.write(data)
+ # empty queue
+ self.queue.truncate(0)
+
+ def writerows(self, rows):
+ for row in rows:
+ self.writerow(row)
\ No newline at end of file