Python 3
[wolnelektury.git] / src / contact / models.py
1 # -*- coding: utf-8 -*-
2 import yaml
3 from hashlib import sha1
4 from django.db import models
5 from django.utils.encoding import smart_text
6 from django.utils.translation import ugettext_lazy as _
7 from jsonfield import JSONField
8 from . import app_settings
9
10
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 = JSONField(_('body'))
17
18     @staticmethod
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)
22             if for_html:
23                 value = smart_text(value).replace(u" ", unichr(160))
24         return value
25
26     class Meta:
27         ordering = ('-created_at',)
28         verbose_name = _('submitted form')
29         verbose_name_plural = _('submitted forms')
30
31     def __str__(self):
32         return str(self.created_at)
33
34     def digest(self):
35         serialized_body = ';'.join(sorted('%s:%s' % item for item in self.body.items()))
36         data = '%s%s%s%s%s' % (self.id, self.contact, serialized_body, self.ip, self.form_tag)
37         return sha1(data).hexdigest()
38
39     def keys(self):
40         try:
41             from .views import contact_forms
42             orig_fields = contact_forms[self.form_tag]().fields
43         except KeyError:
44             orig_fields = {}
45         return list(orig_fields.keys())
46
47     def items(self):
48         return [(key, self.body[key]) for key in self.keys() if key in self.body]
49
50
51 class Attachment(models.Model):
52     contact = models.ForeignKey(Contact)
53     tag = models.CharField(max_length=64)
54     file = models.FileField(upload_to='contact/attachment')
55
56     @models.permalink
57     def get_absolute_url(self):
58         return 'contact_attachment', [self.contact_id, self.tag]
59
60
61 __import__(app_settings.FORMS_MODULE)