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.core.cache import get_cache
7 from django.core.urlresolvers import reverse
8 from django.db import models
9 from django.template.loader import render_to_string
10 from django.utils.safestring import mark_safe
11 from django.utils.translation import get_language, ugettext_lazy as _
12 from newtagging import managers
13 from catalogue.models import Tag
16 permanent_cache = get_cache('permanent')
19 class Fragment(models.Model):
20 """Represents a themed fragment of a book."""
21 text = models.TextField()
22 short_text = models.TextField(editable=False)
23 anchor = models.CharField(max_length=120)
24 book = models.ForeignKey('Book', related_name='fragments')
26 objects = models.Manager()
27 tagged = managers.ModelTaggedItemManager(Tag)
28 tags = managers.TagDescriptor(Tag)
31 ordering = ('book', 'anchor',)
32 verbose_name = _('fragment')
33 verbose_name_plural = _('fragments')
34 app_label = 'catalogue'
36 def get_absolute_url(self):
37 return '%s#m%s' % (reverse('book_text', args=[self.book.slug]), self.anchor)
39 def reset_short_html(self):
43 cache_key = "Fragment.short_html/%d/%s"
44 for lang, langname in settings.LANGUAGES:
45 permanent_cache.delete(cache_key % (self.id, lang))
47 def get_short_text(self):
48 """Returns short version of the fragment."""
49 return self.short_text if self.short_text else self.text
53 cache_key = "Fragment.short_html/%d/%s" % (self.id, get_language())
54 short_html = permanent_cache.get(cache_key)
58 if short_html is not None:
59 return mark_safe(short_html)
61 short_html = unicode(render_to_string('catalogue/fragment_short.html',
64 permanent_cache.set(cache_key, short_html)
65 return mark_safe(short_html)