remove the banner
[wolnelektury.git] / src / catalogue / models / tag.py
index 6aaa97c..a5c96d5 100644 (file)
@@ -1,5 +1,5 @@
-# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
-# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
+# This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
+# Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
 #
 from django.conf import settings
 from django.contrib.contenttypes.fields import GenericForeignKey
 #
 from django.conf import settings
 from django.contrib.contenttypes.fields import GenericForeignKey
@@ -11,28 +11,26 @@ from django.db import models
 from django.db.models.query import Prefetch
 from django.dispatch import Signal
 from django.urls import reverse
 from django.db.models.query import Prefetch
 from django.dispatch import Signal
 from django.urls import reverse
-from django.utils.translation import ugettext_lazy as _
+from django.utils.translation import gettext_lazy as _
 
 from newtagging.models import TagManager, TaggedItemManager
 
 
 
 from newtagging.models import TagManager, TaggedItemManager
 
 
-# Those are hard-coded here so that makemessages sees them.
 TAG_CATEGORIES = (
 TAG_CATEGORIES = (
-    ('author', _('author')),
-    ('epoch', _('epoch')),
-    ('kind', _('kind')),
-    ('genre', _('genre')),
-    ('theme', _('theme')),
-    ('set', _('set')),
-    ('thing', _('thing')),  # things shown on pictures
+    ('author', _('autor')),
+    ('epoch', _('epoka')),
+    ('kind', _('rodzaj')),
+    ('genre', _('gatunek')),
+    ('theme', _('motyw')),
+    ('set', _('półka')),
+    ('thing', _('obiekt')),  # things shown on pictures
 )
 
 
 class TagRelation(models.Model):
 )
 
 
 class TagRelation(models.Model):
-
-    tag = models.ForeignKey('Tag', models.CASCADE, verbose_name=_('tag'), related_name='items')
-    content_type = models.ForeignKey(ContentType, models.CASCADE, verbose_name=_('content type'))
-    object_id = models.PositiveIntegerField(_('object id'), db_index=True)
+    tag = models.ForeignKey('Tag', models.CASCADE, verbose_name='tag', related_name='items')
+    content_type = models.ForeignKey(ContentType, models.CASCADE, verbose_name='typ obiektu')
+    object_id = models.PositiveIntegerField('id obiektu', db_index=True)
     content_object = GenericForeignKey('content_type', 'object_id')
 
     objects = TaggedItemManager()
     content_object = GenericForeignKey('content_type', 'object_id')
 
     objects = TaggedItemManager()
@@ -53,12 +51,12 @@ class Tag(models.Model):
 
     Used to represent searchable metadata (authors, epochs, genres, kinds),
     fragment themes (motifs) and some book hierarchy related kludges."""
 
     Used to represent searchable metadata (authors, epochs, genres, kinds),
     fragment themes (motifs) and some book hierarchy related kludges."""
-    name = models.CharField(_('name'), max_length=120, db_index=True)
-    slug = models.SlugField(_('slug'), max_length=120, db_index=True)
-    sort_key = models.CharField(_('sort key'), max_length=120, db_index=True)
+    name = models.CharField('nazwa', max_length=120, db_index=True)
+    slug = models.SlugField('slug', max_length=120, db_index=True)
+    sort_key = models.CharField('klucz sortowania', max_length=120, db_index=True)
     category = models.CharField(
     category = models.CharField(
-        _('category'), max_length=50, blank=False, null=False, db_index=True, choices=TAG_CATEGORIES)
-    description = models.TextField(_('description'), blank=True)
+        'kategoria', max_length=50, blank=False, null=False, db_index=True, choices=TAG_CATEGORIES)
+    description = models.TextField('opis', blank=True)
 
     for_books = models.BooleanField(default=False)
     for_pictures = models.BooleanField(default=False)
 
     for_books = models.BooleanField(default=False)
     for_pictures = models.BooleanField(default=False)
@@ -67,11 +65,38 @@ class Tag(models.Model):
     gazeta_link = models.CharField(blank=True, max_length=240)
     culturepl_link = models.CharField(blank=True, max_length=240)
     wiki_link = models.CharField(blank=True, max_length=240)
     gazeta_link = models.CharField(blank=True, max_length=240)
     culturepl_link = models.CharField(blank=True, max_length=240)
     wiki_link = models.CharField(blank=True, max_length=240)
-
-    created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
-    changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
-
-    after_change = Signal(providing_args=['instance'])
+    photo = models.FileField(blank=True, null=True, upload_to='catalogue/tag/')
+    photo_attribution = models.CharField(max_length=255, blank=True)
+
+    created_at = models.DateTimeField('data utworzenia', auto_now_add=True, db_index=True)
+    changed_at = models.DateTimeField('data modyfikacji', auto_now=True, db_index=True)
+
+    plural = models.CharField(
+        'liczba mnoga', max_length=255, blank=True,
+        help_text='dotyczy gatunków'
+    )
+    genre_epoch_specific = models.BooleanField(
+        default=False,
+        help_text='Po wskazaniu tego gatunku, dodanie epoki byłoby nadmiarowe, np. „dramat romantyczny”'
+    )
+    adjective_feminine_singular = models.CharField(
+        'przymiotnik pojedynczy żeński', max_length=255, blank=True,
+        help_text='twórczość … Adama Mickiewicza; dotyczy epok'
+    )
+    adjective_nonmasculine_plural = models.CharField(
+        'przymiotnik mnogi niemęskoosobowy', max_length=255, blank=True,
+        help_text='utwory … Adama Mickiewicza; dotyczy epok'
+    )
+    genitive = models.CharField(
+        'dopełniacz', max_length=255, blank=True,
+        help_text='utwory … (czyje?); dotyczy autorów'
+    )
+    collective_noun = models.CharField(
+        'określenie zbiorowe', max_length=255, blank=True,
+        help_text='np. „Liryka” albo „Twórczość dramatyczna”; dotyczy rodzajów'
+    )
+
+    after_change = Signal()
 
     intermediary_table_model = TagRelation
     objects = TagManager()
 
     intermediary_table_model = TagRelation
     objects = TagManager()
@@ -94,15 +119,15 @@ class Tag(models.Model):
 
     class Meta:
         ordering = ('sort_key',)
 
     class Meta:
         ordering = ('sort_key',)
-        verbose_name = _('tag')
-        verbose_name_plural = _('tags')
+        verbose_name = 'tag'
+        verbose_name_plural = 'tagi'
         unique_together = (("slug", "category"),)
         app_label = 'catalogue'
 
         unique_together = (("slug", "category"),)
         app_label = 'catalogue'
 
-    def save(self, *args, **kwargs):
+    def save(self, *args, quick=False, **kwargs):
         existing = self.pk and self.category != 'set'
         ret = super(Tag, self).save(*args, **kwargs)
         existing = self.pk and self.category != 'set'
         ret = super(Tag, self).save(*args, **kwargs)
-        if existing:
+        if existing and not quick:
             self.after_change.send(sender=type(self), instance=self)
         return ret
 
             self.after_change.send(sender=type(self), instance=self)
         return ret
 
@@ -130,9 +155,18 @@ class Tag(models.Model):
     def get_absolute_gallery_url(self):
         return reverse('tagged_object_list_gallery', args=[self.url_chunk])
 
     def get_absolute_gallery_url(self):
         return reverse('tagged_object_list_gallery', args=[self.url_chunk])
 
+    def get_absolute_catalogue_url(self):
+        # TODO: remove magic.
+        if self.category == 'set':
+            return reverse('social_my_shelf')
+        elif self.category == 'thing':
+            return ''
+        else:
+            return reverse(f'{self.category}_catalogue')
+
     def has_description(self):
         return len(self.description) > 0
     def has_description(self):
         return len(self.description) > 0
-    has_description.short_description = _('description')
+    has_description.short_description = 'opis'
     has_description.boolean = True
 
     @staticmethod
     has_description.boolean = True
 
     @staticmethod
@@ -179,41 +213,43 @@ class Tag(models.Model):
         from slugify import slugify
         from sortify import sortify
         meta_tags = []
         from slugify import slugify
         from sortify import sortify
         meta_tags = []
-        categories = (('kinds', 'kind'), ('genres', 'genre'), ('authors', 'author'), ('epochs', 'epoch'))
-        for field_name, category in categories:
+        categories = (
+            # BookInfo field names, Tag category, relationship
+            ('kinds', 'kind', None),
+            ('genres', 'genre', None),
+            ('epochs', 'epoch', None),
+            ('authors', 'author', None),
+            ('translators', 'author', 'translator'),
+        )
+        for field_name, category, relationship in categories:
             try:
                 tag_names = getattr(info, field_name)
             except (AttributeError, KeyError):  # TODO: shouldn't be KeyError here at all.
             try:
                 tag_names = getattr(info, field_name)
             except (AttributeError, KeyError):  # TODO: shouldn't be KeyError here at all.
-                try:
-                    tag_names = [getattr(info, category)]
-                except KeyError:
-                    # For instance, Pictures do not have 'genre' field.
-                    continue
+                # For instance, Pictures do not have 'genre' field.
+                continue
             for tag_name in tag_names:
             for tag_name in tag_names:
-                lang = getattr(tag_name, 'lang', settings.LANGUAGE_CODE)
+                lang = getattr(tag_name, 'lang', None) or settings.LANGUAGE_CODE
                 tag_sort_key = tag_name
                 if category == 'author':
                     tag_sort_key = ' '.join((tag_name.last_name,) + tag_name.first_names)
                     tag_name = tag_name.readable()
                 tag_sort_key = tag_name
                 if category == 'author':
                     tag_sort_key = ' '.join((tag_name.last_name,) + tag_name.first_names)
                     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=slugify(tag_name), category=category)
-                    if created:
-                        tag_name = str(tag_name)
-                        tag.name = tag_name
-                        setattr(tag, "name_%s" % lang, tag_name)
-                        tag.sort_key = sortify(tag_sort_key.lower())
-                        tag.save()
-
-                    meta_tags.append(tag)
+
+                try:
+                    tag = Tag.objects.get(category=category, **{"name_%s" % lang: tag_name})
+                except Tag.DoesNotExist:
+                    if lang == settings.LANGUAGE_CODE:
+                        # Allow creating new tag, if it's in default language.
+                        tag, created = Tag.objects.get_or_create(slug=slugify(tag_name), category=category)
+                        if created:
+                            tag_name = str(tag_name)
+                            tag.name = tag_name
+                            setattr(tag, "name_%s" % lang, tag_name)
+                            tag.sort_key = sortify(tag_sort_key.lower())
+                            tag.save()
+
+                        meta_tags.append((tag, relationship))
                 else:
                 else:
-                    # Ignore unknown tags in non-default languages.
-                    try:
-                        tag = Tag.objects.get(category=category, **{"name_%s" % lang: tag_name})
-                    except Tag.DoesNotExist:
-                        pass
-                    else:
-                        meta_tags.append(tag)
+                    meta_tags.append((tag, relationship))
         return meta_tags
 
 
         return meta_tags