diff options
Diffstat (limited to 'ishtar_common/models.py')
| -rw-r--r-- | ishtar_common/models.py | 174 | 
1 files changed, 120 insertions, 54 deletions
| diff --git a/ishtar_common/models.py b/ishtar_common/models.py index d7e63856b..2a12edc02 100644 --- a/ishtar_common/models.py +++ b/ishtar_common/models.py @@ -42,7 +42,7 @@ from django.core.urlresolvers import reverse, NoReverseMatch  from django.db.utils import DatabaseError  from django.db.models import Q, Max, Count  from django.db.models.base import ModelBase -from django.db.models.signals import post_save, pre_delete +from django.db.models.signals import post_save, pre_delete, post_delete  from django.utils.translation import ugettext_lazy as _, ugettext, \      pgettext_lazy @@ -188,7 +188,7 @@ def valid_ids(cls):                  cls.objects.get(pk=v)              except ObjectDoesNotExist:                  raise ValidationError( -                    _(u"An item selected is not a valid item.")) +                    _(u"A selected item is not a valid item."))      return func @@ -199,7 +199,7 @@ def is_unique(cls, field):          try:              assert cls.objects.filter(**query).count() == 0          except AssertionError: -            raise ValidationError(_(u"This item already exist.")) +            raise ValidationError(_(u"This item already exists."))      return func @@ -249,7 +249,24 @@ class OwnPerms:          return cls.objects.filter(query).order_by(*cls._meta.ordering) -class GeneralType(models.Model): +class Cached(object): +    slug_field = 'txt_idx' + +    @classmethod +    def get_cache(cls, slug): +        cache_key, value = get_cache(cls, slug) +        if value: +            return value +        try: +            k = {cls.slug_field: slug} +            obj = cls.objects.get(**k) +            cache.set(cache_key, obj, settings.CACHE_TIMEOUT) +            return obj +        except cls.DoesNotExist: +            return None + + +class GeneralType(models.Model, Cached):      """      Abstract class for "types"      """ @@ -457,18 +474,6 @@ class GeneralType(models.Model):          for item in cls.objects.all():              item.generate_key() -    @classmethod -    def get_cache(cls, slug): -        cache_key, value = get_cache(cls, slug) -        if value: -            return value -        try: -            obj = cls.objects.get(txt_idx=slug) -            cache.set(cache_key, obj, settings.CACHE_TIMEOUT) -            return obj -        except cls.DoesNotExist: -            return None -  class ItemKey(models.Model):      key = models.CharField(_(u"Key"), max_length=100) @@ -477,7 +482,7 @@ class ItemKey(models.Model):      content_object = generic.GenericForeignKey('content_type', 'object_id')      importer = models.ForeignKey(          'Import', null=True, blank=True, -        help_text=_(u"Key specific to an import")) +        help_text=_(u"Specific key to an import"))      def __unicode__(self):          return self.key @@ -765,7 +770,79 @@ class LightHistorizedItem(BaseHistorizedItem):          return True -class GlobalVar(models.Model): +class IshtarSiteProfile(models.Model, Cached): +    slug_field = 'slug' +    label = models.TextField(_(u"Name")) +    slug = models.SlugField(_(u"Slug"), unique=True) +    description = models.TextField(_(u"Description"), null=True, blank=True) +    files = models.BooleanField(_(u"Files module"), default=False) +    context_record = models.BooleanField(_(u"Context records module"), +                                         default=False) +    find = models.BooleanField(_(u"Finds module"), default=False, +                               help_text=_(u"Need context records module")) +    warehouse = models.BooleanField( +        _(u"Warehouses module"), default=False, +        help_text=_(u"Need finds module")) +    active = models.BooleanField(_(u"Current active"), default=False) + +    class Meta: +        verbose_name = _(u"Ishtar site profile") +        verbose_name_plural = _(u"Ishtar site profiles") +        ordering = ['label'] + +    def __unicode__(self): +        return unicode(self.label) + +    def save(self, *args, **kwargs): +        raw = False +        if 'raw' in kwargs: +            raw = kwargs.pop('raw') +        super(IshtarSiteProfile, self).save(*args, **kwargs) +        obj = self +        if raw: +            return obj +        q = self.__class__.objects.filter(active=True).exclude(slug=self.slug) +        if obj.active and q.count(): +            for profile in q.all(): +                profile.active = False +                profile.save(raw=True) +        changed = False +        if not obj.active and not q.count(): +            obj.active = True +            changed = True +        if obj.warehouse and not obj.find: +            obj.find = True +            changed = True +        if obj.find and not obj.context_record: +            obj.context_record = True +            changed = True +        if changed: +            obj = obj.save(raw=True) +        return obj + + +def get_current_profile(force=False): +    cache_key, value = get_cache(IshtarSiteProfile, ['is-current-profile']) +    if value and not force: +        return value +    q = IshtarSiteProfile.objects.filter(active=True) +    if not q.count(): +        obj = IshtarSiteProfile.objects.create( +            label="Default profile", slug='default', active=True) +    else: +        obj = q.all()[0] +    cache.set(cache_key, obj, settings.CACHE_TIMEOUT) +    return obj + + +def cached_site_changed(sender, **kwargs): +    get_current_profile(force=True) + +post_save.connect(cached_site_changed, sender=IshtarSiteProfile) +post_delete.connect(cached_site_changed, sender=IshtarSiteProfile) + + +class GlobalVar(models.Model, Cached):      slug = models.SlugField(_(u"Variable name"), unique=True)      description = models.TextField(_(u"Description of the variable"),                                     null=True, blank=True) @@ -779,18 +856,6 @@ class GlobalVar(models.Model):      def __unicode__(self):          return unicode(self.slug) -    @classmethod -    def get_cache(cls, slug): -        cache_key, value = get_cache(cls, slug) -        if value: -            return value -        try: -            obj = cls.objects.get(slug=slug) -            cache.set(cache_key, obj.value, settings.CACHE_TIMEOUT) -            return obj.value -        except cls.DoesNotExist: -            return None -  def cached_globalvar_changed(sender, **kwargs):      if not kwargs['instance']: @@ -1174,29 +1239,29 @@ class OrganizationType(GeneralType):          verbose_name_plural = _(u"Organization types")          ordering = ('label',) -MODELS = [ -    ('archaeological_operations.models.Operation', _(u"Operation")), -    ('archaeological_operations.models.ArchaeologicalSite', -     _(u"Archaeological site")), -    ('archaeological_operations.models.Parcel', _(u"Parcels")), -    ('archaeological_operations.models.OperationSource', -     _(u"Operation source")), -] -  IMPORTER_CLASSES = {} -if 'archaeological_files' in settings.INSTALLED_APPS: -    MODELS = [('archaeological_files.models.File', _(u"Archaeological files"))]\ -        + MODELS -    IMPORTER_CLASSES.update({ -        'sra-pdl-files': -        'archaeological_files.data_importer.FileImporterSraPdL'}) -if 'archaeological_context_records' in settings.INSTALLED_APPS: +IMPORTER_CLASSES.update({ +    'sra-pdl-files': +    'archaeological_files.data_importer.FileImporterSraPdL'}) + + +def get_importer_models(): +    MODELS = [ +        ('archaeological_operations.models.Operation', _(u"Operation")), +        ('archaeological_operations.models.ArchaeologicalSite', +         _(u"Archaeological site")), +        ('archaeological_operations.models.Parcel', _(u"Parcels")), +        ('archaeological_operations.models.OperationSource', +         _(u"Operation source")), +    ] +    MODELS = [('archaeological_files.models.File', +              _(u"Archaeological files"))] + MODELS      MODELS = [('archaeological_context_records.models.ContextRecord',                _(u"Context records")), ] + MODELS -if 'archaeological_finds' in settings.INSTALLED_APPS:      MODELS = [('archaeological_finds.models.BaseFind',                _(u"Finds")), ] + MODELS +    return MODELS  def get_model_fields(model): @@ -1234,7 +1299,8 @@ class ImporterType(models.Model):      users = models.ManyToManyField('IshtarUser', verbose_name=_(u"Users"),                                     blank=True, null=True)      associated_models = models.CharField(_(u"Associated model"), -                                         max_length=200, choices=MODELS) +                                         max_length=200, +                                         choices=get_importer_models())      is_template = models.BooleanField(_(u"Is template"), default=False)      unicity_keys = models.CharField(_(u"Unicity keys (separator \";\")"),                                      blank=True, null=True, max_length=500) @@ -1429,7 +1495,7 @@ class ImporterDuplicateField(models.Model):      column = models.ForeignKey(ImporterColumn, related_name='duplicate_fields')      field_name = models.CharField(_(u"Field name"), blank=True, null=True,                                    max_length=200) -    force_new = models.BooleanField(_(u"Force creation of new item"), +    force_new = models.BooleanField(_(u"Force creation of new items"),                                      default=False)      concat = models.BooleanField(_(u"Concatenate with existing"),                                   default=False) @@ -1463,7 +1529,7 @@ class ImportTarget(models.Model):      target = models.CharField(u"Target", max_length=500)      regexp_filter = models.ForeignKey("Regexp", blank=True, null=True)      formater_type = models.ForeignKey("FormaterType") -    force_new = models.BooleanField(_(u"Force creation of new item"), +    force_new = models.BooleanField(_(u"Force creation of new items"),                                      default=False)      concat = models.BooleanField(_(u"Concatenate with existing"),                                   default=False) @@ -1729,7 +1795,7 @@ class Import(models.Model):                                           null=True)      end_date = models.DateTimeField(_(u"End date"), blank=True,                                      null=True, editable=False) -    seconds_remaining = models.IntegerField(_(u"Seconds remaining"), +    seconds_remaining = models.IntegerField(_(u"Remaining seconds"),                                              blank=True, null=True,                                              editable=False) @@ -1895,7 +1961,7 @@ class Organization(Address, Merge, OwnPerms, ValueGetter):          verbose_name = _(u"Organization")          verbose_name_plural = _(u"Organizations")          permissions = ( -            ("view_organization", ugettext(u"Can view all Organization")), +            ("view_organization", ugettext(u"Can view all Organizations")),              ("view_own_organization", ugettext(u"Can view own Organization")),              ("add_own_organization", ugettext(u"Can add own Organization")),              ("change_own_organization", @@ -1950,7 +2016,7 @@ class Person(Address, Merge, OwnPerms, ValueGetter):      TYPE = (          ('Mr', _(u'Mr')),          ('Ms', _(u'Miss')), -        ('Mr and Miss', _(u'Mr and Miss')), +        ('Mr and Miss', _(u'Mr and Mrs')),          ('Md', _(u'Mrs')),          ('Dr', _(u'Doctor')),      ) @@ -1973,7 +2039,7 @@ class Person(Address, Merge, OwnPerms, ValueGetter):          verbose_name = _(u"Person")          verbose_name_plural = _(u"Persons")          permissions = ( -            ("view_person", ugettext(u"Can view all Person")), +            ("view_person", ugettext(u"Can view all Persons")),              ("view_own_person", ugettext(u"Can view own Person")),              ("add_own_person", ugettext(u"Can add own Person")),              ("change_own_person", ugettext(u"Can change own Person")), | 
