1 # -*- coding: utf-8 -*-
2 from django.contrib import admin
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.utils.safestring import mark_safe
7 from django.conf.urls import patterns, url
8 from django.http import HttpResponse, Http404
10 from .utils import csv_prepare
13 class ContactAdminMeta(admin.ModelAdmin.__class__):
14 def __getattr__(cls, name):
15 if name.startswith('admin_list_'):
16 return lambda self: ""
17 raise AttributeError(name)
20 class ContactAdmin(admin.ModelAdmin):
21 __metaclass__ = ContactAdminMeta
22 date_hierarchy = 'created_at'
23 list_display = ['created_at', 'contact', 'form_tag'] + \
24 ["admin_list_%d" % i for i in range(admin_list_width)]
25 fields = ['form_tag', 'created_at', 'contact', 'ip']
26 readonly_fields = ['form_tag', 'created_at', 'contact', 'ip']
27 list_filter = ['form_tag']
30 def admin_list(obj, nr):
32 field_name = contact_forms[obj.form_tag].admin_list[nr]
36 return Contact.pretty_print(obj.body.get(field_name, ''), for_html=True)
38 def __getattr__(self, name):
39 if name.startswith('admin_list_'):
40 nr = int(name[len('admin_list_'):])
41 return lambda obj: self.admin_list(obj, nr)
42 raise AttributeError(name)
44 def change_view(self, request, object_id, from_url='', extra_context=None):
47 instance = Contact.objects.get(pk=object_id)
48 assert isinstance(instance.body, dict)
49 except (Contact.DoesNotExist, AssertionError):
52 # Create readonly fields from the body JSON.
53 body_fields = ['body__%s' % k for k in instance.body.keys()]
54 attachments = list(instance.attachment_set.all())
55 body_fields += ['body__%s' % a.tag for a in attachments]
56 self.readonly_fields.extend(body_fields)
58 # Find the original form.
60 orig_fields = contact_forms[instance.form_tag]().fields
64 # Try to preserve the original order.
66 orig_keys = list(orig_fields.keys())
68 key = orig_keys.pop(0)
69 key = "body__%s" % key
70 if key in body_fields:
71 admin_fields.append(key)
72 body_fields.remove(key)
73 admin_fields.extend(body_fields)
76 (None, {'fields': self.fields}),
77 (_('Body'), {'fields': admin_fields}),
80 # Create field getters for fields and attachments.
81 for k, v in instance.body.items():
82 f = (lambda v: lambda self: v)(Contact.pretty_print(v, for_html=True))
83 f.short_description = orig_fields[k].label if k in orig_fields else _(k)
84 setattr(self, "body__%s" % k, f)
86 download_link = "<a href='%(url)s'>%(url)s</a>"
87 for attachment in attachments:
89 link = mark_safe(download_link % {
90 'url': attachment.get_absolute_url()})
91 f = (lambda v: lambda self: v)(link)
92 f.short_description = orig_fields[k].label if k in orig_fields else _(k)
93 setattr(self, "body__%s" % k, f)
94 return super(ContactAdmin, self).change_view(
95 request, object_id, from_url=from_url, extra_context=extra_context)
97 def changelist_view(self, request, extra_context=None):
99 if 'form_tag' in request.GET:
100 form = contact_forms.get(request.GET['form_tag'])
101 context['extract_types'] = [
102 {'slug': 'all', 'label': _('all')},
103 {'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()
111 url(r'^extract/(?P<form_tag>[\w-]+)/(?P<extract_type_slug>[\w-]+)/$',
112 self.admin_site.admin_view(extract_view), name='contact_extract')
113 ) + super(ContactAdmin, self).get_urls()
116 def extract_view(request, form_tag, extract_type_slug):
118 contacts_by_spec = dict()
119 form = contact_forms.get(form_tag)
120 if form is None and extract_type_slug not in ('contacts', 'all'):
123 q = Contact.objects.filter(form_tag=form_tag)
124 at_year = request.GET.get('created_at__year')
125 at_month = request.GET.get('created_at__month')
127 q = q.filter(created_at__year=at_year)
129 q = q.filter(created_at__month=at_month)
131 # Segregate contacts by body key sets
132 for contact in q.all():
133 if extract_type_slug == 'contacts':
135 elif extract_type_slug == 'all':
136 keys = contact.body.keys() + ['contact']
138 keys = form.get_extract_fields(contact, extract_type_slug)
139 contacts_by_spec.setdefault(tuple(keys), []).append(contact)
141 # Generate list for each body key set
142 for keys, contacts in contacts_by_spec.items():
143 toret += u','.join(keys) + '\n'
144 for contact in contacts:
145 if extract_type_slug == 'contacts':
146 records = [dict(contact=contact.contact)]
147 elif extract_type_slug == 'all':
148 records = [dict(contact=contact.contact, **contact.body)]
150 records = form.get_extract_records(keys, contact, extract_type_slug)
152 for record in records:
154 if key not in record:
156 record[key] = csv_prepare(record[key])
157 toret += u','.join([record[key] for key in keys]) + '\n'
160 response = HttpResponse(toret, content_type='text/csv')
161 response['Content-Disposition'] = 'attachment; filename="kontakt.csv"'
164 admin.site.register(Contact, ContactAdmin)