1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from django.conf import settings
6 from django.contrib.contenttypes.fields import GenericRelation
7 from django.core.cache import caches
8 from django.core.urlresolvers import reverse
9 from django.db import models
10 from django.template.loader import render_to_string
11 from django.utils.safestring import mark_safe
12 from django.utils.translation import get_language, ugettext_lazy as _
13 from newtagging import managers
14 from catalogue.models import Tag
17 permanent_cache = caches['permanent']
20 class Fragment(models.Model):
21 """Represents a themed fragment of a book."""
22 text = models.TextField()
23 short_text = models.TextField(editable=False)
24 anchor = models.CharField(max_length=120)
25 book = models.ForeignKey('Book', related_name='fragments')
27 objects = models.Manager()
28 tagged = managers.ModelTaggedItemManager(Tag)
29 tags = managers.TagDescriptor(Tag)
30 tag_relations = GenericRelation(Tag.intermediary_table_model)
33 ordering = ('book', 'anchor',)
34 verbose_name = _('fragment')
35 verbose_name_plural = _('fragments')
36 app_label = 'catalogue'
38 def get_absolute_url(self):
39 return '%s#m%s' % (reverse('book_text', args=[self.book.slug]), self.anchor)
41 def reset_short_html(self):
45 cache_key = "Fragment.short_html/%d/%s"
46 for lang, langname in settings.LANGUAGES:
47 permanent_cache.delete(cache_key % (self.id, lang))
49 def get_short_text(self):
50 """Returns short version of the fragment."""
51 return self.short_text if self.short_text else self.text
55 cache_key = "Fragment.short_html/%d/%s" % (self.id, get_language())
56 short_html = permanent_cache.get(cache_key)
60 if short_html is not None:
61 return mark_safe(short_html)
63 short_html = unicode(render_to_string('catalogue/fragment_short.html',
66 permanent_cache.set(cache_key, short_html)
67 return mark_safe(short_html)