Fix contact form bug.
[prawokultury.git] / contact / admin.py
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
9
10 class ContactAdminMeta(admin.ModelAdmin.__class__):
11     def __getattr__(cls, name):
12         if name.startswith('admin_list_'):
13             return lambda self: ""
14         raise AttributeError, name
15
16
17 class ContactAdmin(admin.ModelAdmin):
18     __metaclass__ = ContactAdminMeta
19     date_hierarchy = 'created_at'
20     list_display = ['created_at', 'contact', 'form_tag'] + \
21         ["admin_list_%d" % i for i in range(admin_list_width)]
22     fields = ['form_tag', 'created_at', 'contact', 'ip']
23     readonly_fields = ['form_tag', 'created_at', 'contact', 'ip']
24     list_filter = ['form_tag']
25
26     def admin_list(self, obj, nr):
27         try:
28             field_name = contact_forms[obj.form_tag].admin_list[nr]
29         except BaseException, e:
30             return ''
31         else:
32             return obj.body.get(field_name, '')
33
34     def __getattr__(self, name):
35         if name.startswith('admin_list_'):
36             nr = int(name[len('admin_list_'):])
37             return lambda obj: self.admin_list(obj, nr)
38         raise AttributeError, name
39
40     def change_view(self, request, object_id, extra_context=None):
41         if object_id:
42             try:
43                 instance = Contact.objects.get(pk=object_id)
44                 assert isinstance(instance.body, dict)
45             except (Contact.DoesNotExist, AssertionError):
46                 pass
47             else:
48                 # Create readonly fields from the body JSON.
49                 body_fields = ['body__%s' % k for k in instance.body.keys()]
50                 attachments = list(instance.attachment_set.all())
51                 body_fields += ['body__%s' % a.tag for a in attachments]
52                 self.readonly_fields.extend(body_fields)
53
54                 # Find the original form.
55                 try:
56                     orig_fields = contact_forms[instance.form_tag]().fields
57                 except KeyError:
58                     orig_fields = {}
59
60                 # Try to preserve the original order.
61                 admin_fields = []
62                 orig_keys = list(orig_fields.keys())
63                 while orig_keys:
64                     key = orig_keys.pop(0)
65                     key = "body__%s" % key
66                     if key in body_fields:
67                         admin_fields.append(key)
68                         body_fields.remove(key)
69                 admin_fields.extend(body_fields)
70
71                 self.fieldsets = [
72                     (None, {'fields': self.fields}),
73                     (_('Body'), {'fields': admin_fields}),
74                 ]
75
76                 # Create field getters for fields and attachments.
77                 for k, v in instance.body.items():
78                     f = (lambda v: lambda self: v)(v)
79                     f.short_description = orig_fields[k].label if k in orig_fields else _(k)
80                     setattr(self, "body__%s" % k, f)
81
82                 download_link = "<a href='%(url)s'>%(url)s</a>"
83                 for attachment in attachments:
84                     k = attachment.tag
85                     link = mark_safe(download_link % {
86                             'url': attachment.get_absolute_url()})
87                     f = (lambda v: lambda self: v)(link)
88                     f.short_description = orig_fields[k].label if k in orig_fields else _(k)
89                     setattr(self, "body__%s" % k, f)
90         return super(ContactAdmin, self).change_view(request, object_id,
91             extra_context=extra_context)
92
93
94 admin.site.register(Contact, ContactAdmin)