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.__metaclass__):
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']
25 def admin_list(self, obj, nr):
27 field_name = contact_forms[obj.form_tag].admin_list[nr]
28 except BaseException, e:
31 return obj.body.get(field_name, '')
33 def __getattr__(self, name):
34 if name.startswith('admin_list_'):
35 nr = int(name[len('admin_list_'):])
36 return lambda obj: self.admin_list(obj, nr)
37 raise AttributeError, name
39 def change_view(self, request, object_id, extra_context=None):
42 instance = Contact.objects.get(pk=object_id)
43 assert isinstance(instance.body, dict)
44 except (Contact.DoesNotExist, AssertionError):
47 # Create readonly fields from the body JSON.
48 body_fields = ['body__%s' % k for k in instance.body.keys()]
49 attachments = list(instance.attachment_set.all())
50 body_fields += ['body__%s' % a.tag for a in attachments]
51 self.readonly_fields.extend(body_fields)
53 # Find the original form.
55 orig_fields = contact_forms[instance.form_tag]().fields
59 # Try to preserve the original order.
61 orig_keys = list(orig_fields.keys())
63 key = orig_keys.pop(0)
64 key = "body__%s" % key
65 if key in body_fields:
66 admin_fields.append(key)
67 body_fields.remove(key)
68 admin_fields.extend(body_fields)
71 (None, {'fields': self.fields}),
72 (_('Body'), {'fields': admin_fields}),
75 # Create field getters for fields and attachments.
76 for k, v in instance.body.items():
77 f = (lambda v: lambda self: v)(v)
78 f.short_description = orig_fields[k].label if k in orig_fields else _(k)
79 setattr(self, "body__%s" % k, f)
81 download_link = "<a href='%(url)s'>%(url)s</a>"
82 for attachment in attachments:
84 link = mark_safe(download_link % {
85 'url': attachment.get_absolute_url()})
86 f = (lambda v: lambda self: v)(link)
87 f.short_description = orig_fields[k].label if k in orig_fields else _(k)
88 setattr(self, "body__%s" % k, f)
89 return super(ContactAdmin, self).change_view(request, object_id,
90 extra_context=extra_context)
93 admin.site.register(Contact, ContactAdmin)