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
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
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']
26 def admin_list(self, obj, nr):
28 field_name = contact_forms[obj.form_tag].admin_list[nr]
29 except BaseException, e:
32 return obj.body.get(field_name, '')
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
40 def change_view(self, request, object_id, extra_context=None):
43 instance = Contact.objects.get(pk=object_id)
44 assert isinstance(instance.body, dict)
45 except (Contact.DoesNotExist, AssertionError):
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)
54 # Find the original form.
56 orig_fields = contact_forms[instance.form_tag]().fields
60 # Try to preserve the original order.
62 orig_keys = list(orig_fields.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)
72 (None, {'fields': self.fields}),
73 (_('Body'), {'fields': admin_fields}),
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)
82 download_link = "<a href='%(url)s'>%(url)s</a>"
83 for attachment in attachments:
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)
94 admin.site.register(Contact, ContactAdmin)