fix after merge
[edumed.git] / contact / models.py
1 # -*- coding: utf-8 -*-
2 import yaml
3 from hashlib import sha1
4 import random
5 import string
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
12
13
14 KEY_SIZE = 30
15
16
17 def make_key(length):
18     return ''.join(
19         random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
20         for i in range(length))
21
22
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)
30
31     @classmethod
32     def generate_key(cls):
33         key = ''
34         while not key or cls.objects.filter(key=key).exists():
35             key = make_key(KEY_SIZE)
36         return key
37
38     @staticmethod
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)
42             if for_html:
43                 value = smart_unicode(value).replace(u" ", unichr(160))
44         return value
45
46     class Meta:
47         ordering = ('-created_at',)
48         verbose_name = _('submitted form')
49         verbose_name_plural = _('submitted forms')
50
51     def __unicode__(self):
52         return unicode(self.created_at)
53
54     def digest(self):
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()
59
60     @permalink
61     def update_url(self):
62         return 'edit_form', [], {'form_tag': self.form_tag, 'contact_id': self.id, 'key': self.key}
63
64
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')
69
70     @models.permalink
71     def get_absolute_url(self):
72         return 'contact_attachment', [self.contact_id, self.tag]
73
74     @property
75     @models.permalink
76     def url(self):
77         return 'contact_attachment_key', [self.contact_id, self.tag, self.contact.key]
78
79     def __unicode__(self):
80         return self.file.name.rsplit('/', 1)[-1]
81
82
83 __import__(app_settings.FORMS_MODULE)