1 from django.contrib import admin
2 from django.forms import ModelForm
3 from .models import Contact
4 from django.utils.translation import ugettext as _
5 from .forms import contact_forms, admin_list_width
6 from django.template import Template
7 from django.utils.safestring import mark_safe
8 from django.conf.urls import patterns, url
9 from django.http import HttpResponse, Http404
11 from .utils import deunicode
12 from StringIO import StringIO
13 from csv import writer
16 class ContactAdminMeta(admin.ModelAdmin.__class__):
17 def __getattr__(cls, name):
18 if name.startswith('admin_list_'):
19 return lambda self: ""
20 raise AttributeError, name
23 class ContactAdmin(admin.ModelAdmin):
24 __metaclass__ = ContactAdminMeta
25 date_hierarchy = 'created_at'
26 list_display = ['created_at', 'contact', 'form_tag'] + \
27 ["admin_list_%d" % i for i in range(admin_list_width)]
28 fields = ['form_tag', 'created_at', 'contact', 'ip', 'key']
29 readonly_fields = ['form_tag', 'created_at', 'contact', 'ip', 'key']
30 list_filter = ['form_tag']
32 def admin_list(self, obj, nr):
34 field_name = contact_forms[obj.form_tag].admin_list[nr]
35 except BaseException, e:
38 return obj.body.get(field_name, '')
40 def __getattr__(self, name):
41 if name.startswith('admin_list_'):
42 nr = int(name[len('admin_list_'):])
43 return lambda obj: self.admin_list(obj, nr)
44 raise AttributeError, name
46 def change_view(self, request, object_id, extra_context=None):
49 instance = Contact.objects.get(pk=object_id)
50 assert isinstance(instance.body, dict)
51 except (Contact.DoesNotExist, AssertionError):
54 # Create readonly fields from the body JSON.
55 body_fields = ['body__%s' % k for k in instance.body.keys()]
56 attachments = list(instance.attachment_set.all())
57 body_fields += ['body__%s' % a.tag for a in attachments]
58 self.readonly_fields.extend(body_fields)
60 # Find the original form.
62 orig_fields = contact_forms[instance.form_tag]().fields
66 # Try to preserve the original order.
68 orig_keys = list(orig_fields.keys())
70 key = orig_keys.pop(0)
71 key = "body__%s" % key
72 if key in body_fields:
73 admin_fields.append(key)
74 body_fields.remove(key)
75 admin_fields.extend(body_fields)
78 (None, {'fields': self.fields}),
79 (_('Body'), {'fields': admin_fields}),
82 # Create field getters for fields and attachments.
83 for k, v in instance.body.items():
84 f = (lambda v: lambda self: v)(v)
85 f.short_description = orig_fields[k].label if k in orig_fields else _(k)
86 setattr(self, "body__%s" % k, f)
88 download_link = "<a href='%(url)s'>%(url)s</a>"
89 for attachment in attachments:
91 link = mark_safe(download_link % {
92 'url': attachment.get_absolute_url()})
93 f = (lambda v: lambda self: v)(link)
94 f.short_description = orig_fields[k].label if k in orig_fields else _(k)
95 setattr(self, "body__%s" % k, f)
96 return super(ContactAdmin, self).change_view(request, object_id,
97 extra_context=extra_context)
99 def changelist_view(self, request, extra_context=None):
101 if 'form_tag' in request.GET:
102 form = contact_forms.get(request.GET['form_tag'])
103 context['extract_types'] = [dict(slug = 'all', label = _('all'))] + [dict(slug = 'contacts', label = _('contacts'))]
104 context['extract_types'] += [type for type in getattr(form, 'extract_types', [])]
105 return super(ContactAdmin, self).changelist_view(request, extra_context = context)
108 urls = super(ContactAdmin, self).get_urls()
110 url(r'^extract/(?P<form_tag>[\w-]+)/(?P<extract_type_slug>[\w-]+)/$', self.admin_site.admin_view(extract_view), name='contact_extract')
111 ) + super(ContactAdmin, self).get_urls()
114 def extract_view(request, form_tag, extract_type_slug):
116 toret = writer(retval)
117 contacts_by_spec = dict()
119 form = [f for f in contact_forms.values() if f.save_as_tag == form_tag][0]
122 if form is None and extract_type_slug not in ('contacts', 'all'):
125 q = Contact.objects.filter(form_tag = form_tag)
126 at_year = request.GET.get('created_at__year')
127 at_month = request.GET.get('created_at__month')
129 q = q.filter(created_at__year = at_year)
131 q = q.filter(created_at__month = at_month)
133 if extract_type_slug == 'contacts':
134 keys = set(['contact'])
136 keys = set(['contact', 'ip', 'created_at'])
137 for contact in q.all():
138 if extract_type_slug == 'all':
139 keys.update(contact.body.keys())
141 keys.update(form.get_extract_fields(contact, extract_type_slug))
144 key_labels = {f.name: f.verbose_name.encode('utf-8') for f in Contact._meta.fields}
147 key_labels.update({k: v.label.encode('utf-8') for (k, v) in fi.fields.items()})
149 toret.writerow([key_labels.get(key, key) for key in keys])
150 for contact in q.all():
151 if extract_type_slug == 'contacts':
152 records = [dict(contact=contact.contact)]
153 elif extract_type_slug == 'all':
154 records = [dict(contact = contact.contact, ip=contact.ip, created_at=contact.created_at, **contact.body)]
156 records = form.get_extract_records(keys, contact, extract_type_slug)
158 for record in records:
159 toret.writerow([deunicode(record.get(key, '-')) for key in keys])
161 response = HttpResponse(retval.getvalue(), content_type = 'text/csv')
162 response['Content-Disposition'] = 'attachment; filename="%s.csv"' % form_tag
165 admin.site.register(Contact, ContactAdmin)