block tags, bleh (migdal compatibility)
[prawokultury.git] / contact / management / commands / contact_csv.py
1 # -*- coding: utf-8 -*-
2
3 from optparse import make_option
4 from django.core.management.base import BaseCommand
5
6 class Command(BaseCommand):
7     option_list = BaseCommand.option_list + (
8         make_option('-e', '--exclude-fields', dest='exclude', metavar='name,...', default='',
9             help='Exclude specific body fields by name'),
10         make_option('-m', '--mailto', dest='mailto', metavar='email,...', default='',
11             help='Send by mail'),
12     )
13     help = 'Dump form entries in a csv file.'
14     def handle(self, *args, **kwargs):
15         from csv import writer
16         from sys import stdout
17         from django.conf import settings
18         from django.core.mail import EmailMessage
19         from contact.models import Contact
20         from StringIO import StringIO
21
22         excludes = set(kwargs['exclude'].split(','))
23
24         buffer = StringIO()
25         w = writer(buffer)
26
27         lines = []
28         headers = set()
29         for c in Contact.objects.filter(form_tag__in=args):
30             headers |= set(c.body.keys())
31             lines.append(c)
32         headers = sorted(headers - excludes)
33         w.writerow([u'email'] + headers)
34         for c in lines:
35             row = [c.contact.encode('utf-8')]
36             for h in headers:
37                 v = c.body.get(h)
38                 if isinstance(v, unicode):
39                     v = v.encode('utf-8') 
40                 row.append(v)
41             w.writerow(row)
42
43         mailto = kwargs['mailto']
44         if mailto:
45             mailto = mailto.split(',')
46             message = EmailMessage('Contacts CSV', 'Contacts CSV', settings.CONTACT_EMAIL, mailto)
47             message.attach('contacts.csv', buffer.getvalue(), 'text/csv')
48             message.send()
49         else:
50             print buffer.getvalue()
51