add update forms
[edumed.git] / 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_unicode, force_str
6 from django.db.models import permalink
7 from django.utils.translation import ugettext_lazy as _
8 from jsonfield import JSONField
9 from . import app_settings
10
11
12 class Contact(models.Model):
13     created_at = models.DateTimeField(_('submission date'), auto_now_add=True)
14     ip = models.IPAddressField(_('IP address'))
15     contact = models.CharField(_('contact'), max_length=128)
16     form_tag = models.CharField(_('form'), max_length=32, db_index=True)
17     body = JSONField(_('body'))
18
19     @staticmethod
20     def pretty_print(value, for_html=False):
21         if type(value) in (tuple, list, dict):
22             value = yaml.safe_dump(value, allow_unicode=True, default_flow_style=False)
23             if for_html:
24                 value = smart_unicode(value).replace(u" ", unichr(160))
25         return value
26
27     class Meta:
28         ordering = ('-created_at',)
29         verbose_name = _('submitted form')
30         verbose_name_plural = _('submitted forms')
31
32     def __unicode__(self):
33         return unicode(self.created_at)
34
35     def digest(self):
36         serialized_body = ';'.join(sorted('%s:%s' % item for item in self.body.iteritems()))
37         data = '%s%s%s%s%s' % (self.id, self.contact, serialized_body, self.ip, self.form_tag)
38         data = force_str(data)
39         return sha1(data).hexdigest()
40
41     @permalink
42     def update_url(self):
43         from contact.forms import update_forms, contact_forms
44         form_class = update_forms.get(self.form_tag, contact_forms.get(self.form_tag))
45         confirmation = form_class.confirmation_class.objects.get(contact=self)
46         return 'edit_form', [], {'form_tag': self.form_tag, 'contact_id': self.id, 'key': confirmation.key}
47
48
49 class Attachment(models.Model):
50     contact = models.ForeignKey(Contact)
51     tag = models.CharField(max_length=64)
52     file = models.FileField(upload_to='contact/attachment')
53
54     @models.permalink
55     def get_absolute_url(self):
56         return 'contact_attachment', [self.contact_id, self.tag]
57
58
59 __import__(app_settings.FORMS_MODULE)