1 # -*- coding: utf-8 -*-
3 from hashlib import sha1
6 from django.db import models
7 from django.utils.encoding import smart_unicode, force_str
8 from django.db.models import permalink
9 from django.utils.translation import ugettext_lazy as _
10 from jsonfield import JSONField
11 from . import app_settings
19 random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
20 for i in range(length))
23 class Contact(models.Model):
24 created_at = models.DateTimeField(_('submission date'), auto_now_add=True)
25 ip = models.IPAddressField(_('IP address'))
26 contact = models.CharField(_('contact'), max_length=128)
27 form_tag = models.CharField(_('form'), max_length=32, db_index=True)
28 body = JSONField(_('body'))
29 key = models.CharField(max_length=KEY_SIZE)
31 def generate_key(self):
33 while not key or Contact.objects.filter(key=key).exists():
34 key = make_key(KEY_SIZE)
39 def pretty_print(value, for_html=False):
40 if type(value) in (tuple, list, dict):
41 value = yaml.safe_dump(value, allow_unicode=True, default_flow_style=False)
43 value = smart_unicode(value).replace(u" ", unichr(160))
47 ordering = ('-created_at',)
48 verbose_name = _('submitted form')
49 verbose_name_plural = _('submitted forms')
51 def __unicode__(self):
52 return unicode(self.created_at)
55 serialized_body = ';'.join(sorted('%s:%s' % item for item in self.body.iteritems()))
56 data = '%s%s%s%s%s' % (self.id, self.contact, serialized_body, self.ip, self.form_tag)
57 data = force_str(data)
58 return sha1(data).hexdigest()
62 return 'edit_form', [], {'form_tag': self.form_tag, 'contact_id': self.id, 'key': self.key}
65 class Attachment(models.Model):
66 contact = models.ForeignKey(Contact)
67 tag = models.CharField(max_length=64)
68 file = models.FileField(upload_to='contact/attachment')
71 def get_absolute_url(self):
72 return 'contact_attachment', [self.contact_id, self.tag]
77 return 'contact_attachment_key', [self.contact_id, self.tag, self.contact.key]
79 def __unicode__(self):
80 return self.file.name.rsplit('/', 1)[-1]
83 __import__(app_settings.FORMS_MODULE)