Project

General

Profile

Download (1.52 KB) Statistics
| Branch: | Tag: | Revision:

root / entrouvert / djommon / multitenant / models.py @ c59fb59b

1
import re
2
import json
3

    
4
from django.utils.translation import ugettext as _
5
from django.db import models
6
from django.core.exceptions import ImproperlyConfigured
7

    
8
from tenant_schemas.models import TenantMixin
9

    
10
from . import app_settings
11

    
12
class Tenant(TenantMixin):
13
    name = models.CharField(max_length=100, verbose_name=_('name'))
14
    created_on = models.DateField(auto_now_add=True, verbose_name=_('created on'))
15
    is_active = models.BooleanField(default=True, blank=True, verbose_name=_('active'))
16

    
17

    
18
    # default true, schema will be automatically created and synced when it is saved
19
    auto_create_schema = False
20

    
21
class ClientSetting(models.Model):
22
    NAME_RE = re.compile(r'^[_A-Z][_A-Z0-9]*$')
23

    
24
    tenant = models.ForeignKey('Tenant', verbose_name=_('tenant'))
25
    name = models.CharField(max_length=100, verbose_name=_('name'))
26
    value = models.TextField(verbose_name=_('value'), help_text=_('JSON'))
27

    
28
    def get_json(self):
29
        return json.loads(self.value)
30

    
31
    def set_json(self, json):
32
        self.value = json.dumps(json)
33

    
34
    json = property(get_json, set_json)
35

    
36
    def clean(self):
37
        if not re.match(self.NAME_RE, self.name):
38
            raise models.ValidationError('name must be an uppercase variable '
39
                    'name')
40
        try:
41
            json.loads(self.value)
42
        except ValueError:
43
            raise models.ValidationError('invalid JSON document')
44
        if self.name in dir(app_settings):
45
            raise ImproperlyConfigured('The setting %r cannot be overridden by tenants' % self.name)
46

    
(5-5/8)