local changes from server
[prawokultury.git] / contact / models.py
1 # -*- coding: utf-8 -*-
2 import random
3 import string
4 from django.core.files.storage import FileSystemStorage
5 from django.db import models
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.IPAddressField(_('IP address'), default='127.0.0.1')
14     contact = models.CharField(_('contact'), max_length=128)
15     form_tag = models.CharField(_('form'), max_length=32, db_index=True)
16     body = JSONField(_('body'))
17     key = models.CharField(_('key'), max_length=64, db_index=True, blank=True)
18
19     class Meta:
20         ordering = ('-created_at',)
21         verbose_name = _('submitted form')
22         verbose_name_plural = _('submitted forms')
23
24     def __unicode__(self):
25         return unicode(self.created_at)
26
27     def save(self, *args, **kwargs):
28         if not self.key:
29             self.key = self.generate_key()
30         return super(Contact, self).save(*args, **kwargs)
31
32     @classmethod
33     def generate_key(cls):
34         key = ''
35         while not key or key in [record['key'] for record in cls.objects.values('key')]:
36             key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for i in range(30))
37         return key
38
39
40 class Attachment(models.Model):
41     contact = models.ForeignKey(Contact)
42     tag = models.CharField(max_length=64)
43     file = models.FileField(upload_to='contact/attachment')
44
45     @models.permalink
46     def get_absolute_url(self):
47         return ('contact_attachment', [self.contact_id, self.tag])
48
49
50 __import__(app_settings.FORMS_MODULE)