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
6 from django.template import Template
7 from django.utils.safestring import mark_safe
10 class ContactAdmin(admin.ModelAdmin):
11 date_hierarchy = 'created_at'
12 list_display = ('created_at', 'contact', 'form_tag')
13 fields = ['form_tag', 'created_at', 'contact', 'ip']
14 readonly_fields = ['form_tag', 'created_at', 'contact', 'ip']
16 def change_view(self, request, object_id, extra_context=None):
19 instance = Contact.objects.get(pk=object_id)
20 assert isinstance(instance.body, dict)
21 except (Contact.DoesNotExist, AssertionError):
24 # Create readonly fields from the body JSON.
25 body_fields = ['body__%s' % k for k in instance.body.keys()]
26 attachments = list(instance.attachment_set.all())
27 body_fields += ['body__%s' % a.tag for a in attachments]
28 self.readonly_fields.extend(body_fields)
30 # Find the original form.
32 orig_fields = contact_forms[instance.form_tag]().fields
36 # Try to preserve the original order.
38 orig_keys = list(orig_fields.keys())
40 key = orig_keys.pop(0)
41 key = "body__%s" % key
42 if key in body_fields:
43 admin_fields.append(key)
44 body_fields.remove(key)
45 admin_fields.extend(body_fields)
48 (None, {'fields': self.fields}),
49 (_('Body'), {'fields': admin_fields}),
52 # Create field getters for fields and attachments.
53 for k, v in instance.body.items():
54 f = (lambda v: lambda self: v)(v)
55 f.short_description = orig_fields[k].label if k in orig_fields else _(k)
56 setattr(self, "body__%s" % k, f)
58 download_link = "<a href='%(url)s'>%(url)s</a>"
59 for attachment in attachments:
61 link = mark_safe(download_link % {
62 'url': attachment.get_absolute_url()})
63 f = (lambda v: lambda self: v)(link)
64 f.short_description = orig_fields[k].label if k in orig_fields else _(k)
65 setattr(self, "body__%s" % k, f)
66 return super(ContactAdmin, self).change_view(request, object_id,
67 extra_context=extra_context)
70 admin.site.register(Contact, ContactAdmin)