1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from django.conf import settings
5 from django.contrib.contenttypes.fields import GenericRelation
6 from django.urls import reverse
7 from django.db import models
8 from django.utils.translation import gettext_lazy as _
9 from newtagging import managers
10 from catalogue.models import Tag
11 from wolnelektury.utils import cached_render, clear_cached_renders
14 class Fragment(models.Model):
15 """Represents a themed fragment of a book."""
16 text = models.TextField()
17 short_text = models.TextField(editable=False)
18 anchor = models.CharField(max_length=120)
19 book = models.ForeignKey('Book', models.CASCADE, related_name='fragments')
21 objects = models.Manager()
22 tagged = managers.ModelTaggedItemManager(Tag)
23 tags = managers.TagDescriptor(Tag)
24 tag_relations = GenericRelation(Tag.intermediary_table_model)
27 ordering = ('book', 'anchor',)
28 verbose_name = _('fragment')
29 verbose_name_plural = _('fragments')
30 app_label = 'catalogue'
32 def get_absolute_url(self):
33 return '%s#m%s' % (reverse('book_text', args=[self.book.slug]), self.anchor)
35 def get_api_url(self):
36 return reverse('catalogue_api_fragment', args=[self.book.slug, self.anchor])
38 def get_short_text(self):
39 """Returns short version of the fragment."""
40 return self.short_text if self.short_text else self.text
42 @cached_render('catalogue/fragment_short.html')
44 return {'fragment': self}
46 @cached_render('catalogue/fragment_promo.html')
48 return {'fragment': self}
52 return self.tags.filter(category='theme')
54 def clear_cache(self):
55 clear_cached_renders(self.midi_box)
56 clear_cached_renders(self.promo_box)