3 from hashlib import sha1
4 from django.db import models
5 from django.urls import reverse
6 from django.utils.encoding import smart_text
7 from django.utils.translation import ugettext_lazy as _
8 from . import app_settings
11 class Contact(models.Model):
12 created_at = models.DateTimeField(_('submission date'), auto_now_add=True)
13 ip = models.GenericIPAddressField(_('IP address'))
14 contact = models.EmailField(_('contact'), max_length=128)
15 form_tag = models.CharField(_('form'), max_length=32, db_index=True)
16 body = models.TextField(_('body'))
19 def pretty_print(value, for_html=False):
20 if type(value) in (tuple, list, dict):
21 value = yaml.safe_dump(value, allow_unicode=True, default_flow_style=False)
23 value = smart_text(value).replace(u" ", unichr(160))
27 ordering = ('-created_at',)
28 verbose_name = _('submitted form')
29 verbose_name_plural = _('submitted forms')
32 return str(self.created_at)
35 serialized_body = ';'.join(sorted('%s:%s' % item for item in self.get_body_json().items()))
36 data = '%s%s%s%s%s' % (self.id, self.contact, serialized_body, self.ip, self.form_tag)
37 return sha1(data).hexdigest()
41 from .views import contact_forms
42 orig_fields = contact_forms[self.form_tag]().fields
45 return list(orig_fields.keys())
48 body = self.get_body_json()
49 return [(key, body[key]) for key in self.keys() if key in body]
51 def get_body_json(self):
52 return json.loads(self.body or '{}')
55 class Attachment(models.Model):
56 contact = models.ForeignKey(Contact, models.CASCADE)
57 tag = models.CharField(max_length=64)
58 file = models.FileField(upload_to='contact/attachment')
60 def get_absolute_url(self):
61 return reverse('contact_attachment', args=[self.contact_id, self.tag])
64 __import__(app_settings.FORMS_MODULE)