Add HotJar on few pages.
[wolnelektury.git] / src / catalogue / models / tag.py
index 1531973..c6b6f26 100644 (file)
@@ -3,10 +3,14 @@
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
 from django.conf import settings
+from django.contrib.contenttypes.fields import GenericForeignKey
+from django.contrib.contenttypes.models import ContentType
 from django.core.cache import caches
 from django.contrib.auth.models import User
+from django.core.exceptions import ObjectDoesNotExist
 from django.db import models
 from django.db.models import permalink
+from django.db.models.query import Prefetch
 from django.dispatch import Signal
 from django.utils.translation import ugettext_lazy as _
 
@@ -26,6 +30,24 @@ TAG_CATEGORIES = (
 )
 
 
+class TagRelation(models.Model):
+
+    tag = models.ForeignKey('Tag', verbose_name=_('tag'), related_name='items')
+    content_type = models.ForeignKey(ContentType, verbose_name=_('content type'))
+    object_id = models.PositiveIntegerField(_('object id'), db_index=True)
+    content_object = GenericForeignKey('content_type', 'object_id')
+
+    class Meta:
+        db_table = 'catalogue_tag_relation'
+        unique_together = (('tag', 'content_type', 'object_id'),)
+
+    def __unicode__(self):
+        try:
+            return u'%s [%s]' % (self.content_type.get_object_for_this_type(pk=self.object_id), self.tag)
+        except ObjectDoesNotExist:
+            return u'<deleted> [%s]' % self.tag
+
+
 class Tag(TagBase):
     """A tag attachable to books and fragments (and possibly anything).
 
@@ -38,6 +60,9 @@ class Tag(TagBase):
         _('category'), max_length=50, blank=False, null=False, db_index=True, choices=TAG_CATEGORIES)
     description = models.TextField(_('description'), blank=True)
 
+    for_books = models.BooleanField(default=False)
+    for_pictures = models.BooleanField(default=False)
+
     user = models.ForeignKey(User, blank=True, null=True)
     gazeta_link = models.CharField(blank=True, max_length=240)
     culturepl_link = models.CharField(blank=True, max_length=240)
@@ -48,6 +73,8 @@ class Tag(TagBase):
 
     after_change = Signal(providing_args=['instance', 'languages'])
 
+    intermediary_table_model = TagRelation
+
     class UrlDeprecationWarning(DeprecationWarning):
         def __init__(self, tags=None):
             super(Tag.UrlDeprecationWarning, self).__init__()
@@ -139,6 +166,10 @@ class Tag(TagBase):
         else:
             return ''
 
+    @property
+    def category_plural(self):
+        return self.category + 's'
+
     @permalink
     def get_absolute_url(self):
         return 'tagged_object_list', [self.url_chunk]
@@ -203,7 +234,7 @@ class Tag(TagBase):
 
     @staticmethod
     def tags_from_info(info):
-        from fnpdjango.utils.text.slughifi import slughifi
+        from slugify import slugify
         from sortify import sortify
         meta_tags = []
         categories = (('kinds', 'kind'), ('genres', 'genre'), ('authors', 'author'), ('epochs', 'epoch'))
@@ -224,7 +255,7 @@ class Tag(TagBase):
                     tag_name = tag_name.readable()
                 if lang == settings.LANGUAGE_CODE:
                     # Allow creating new tag, if it's in default language.
-                    tag, created = Tag.objects.get_or_create(slug=slughifi(tag_name), category=category)
+                    tag, created = Tag.objects.get_or_create(slug=slugify(tag_name), category=category)
                     if created:
                         tag_name = unicode(tag_name)
                         tag.name = tag_name
@@ -244,5 +275,16 @@ class Tag(TagBase):
         return meta_tags
 
 
-# Pickle complains about not having this.
-TagRelation = Tag.intermediary_table_model
+def prefetch_relations(objects, category, only_name=True):
+    queryset = TagRelation.objects.filter(tag__category=category).select_related('tag')
+    if only_name:
+        queryset = queryset.only('tag__name_pl', 'object_id')
+    return objects.prefetch_related(
+        Prefetch('tag_relations', queryset=queryset, to_attr='%s_relations' % category))
+
+
+def prefetched_relations(obj, category):
+    if hasattr(obj, '%s_relations' % category):
+        return getattr(obj, '%s_relations' % category)
+    else:
+        return None