gremmie@1: """ gremmie@1: Models for the smiley application. gremmie@1: """ gremmie@1: from django.db import models bgneal@123: from django.core.cache import cache bgneal@123: bgneal@128: CACHE_TIMEOUT = 60 * 60 # seconds gremmie@1: gremmie@1: gremmie@1: class SmileyManager(models.Manager): gremmie@1: gremmie@1: def get_smiley_map(self): bgneal@128: """ bgneal@128: Returns a dictionary of 2-tuples, indexed by smiley codes. bgneal@128: Element 0 of the tuple is the HTML representation of the smiley, bgneal@128: and element 1 is the markdown version. bgneal@128: The dictionary is cached. bgneal@128: """ bgneal@123: map = cache.get('smiley_map') bgneal@123: if map: bgneal@123: return map gremmie@1: bgneal@128: map = dict((s.code, (s.html(), s.markdown())) for s in self.all()) bgneal@123: cache.set('smiley_map', map, CACHE_TIMEOUT) bgneal@123: return map gremmie@1: bgneal@123: def get_smilies(self, extra=False): bgneal@123: key = 'smileys' if not extra else 'smileys_extra' bgneal@123: smilies = cache.get(key) bgneal@123: if smilies: bgneal@123: return smilies bgneal@123: bgneal@123: smilies = self.filter(is_extra=extra) bgneal@123: cache.set(key, smilies, CACHE_TIMEOUT) bgneal@123: return smilies gremmie@1: gremmie@1: gremmie@1: class Smiley(models.Model): gremmie@1: image = models.ImageField(upload_to='smiley/images/') gremmie@1: title = models.CharField(max_length=32) gremmie@1: code = models.CharField(max_length=32) bgneal@123: is_extra = models.BooleanField() gremmie@1: gremmie@1: objects = SmileyManager() gremmie@1: gremmie@1: class Meta: gremmie@1: verbose_name_plural = 'Smilies' gremmie@1: ordering = ('title', ) gremmie@1: gremmie@1: def __unicode__(self): gremmie@1: return self.title gremmie@1: gremmie@1: def get_absolute_url(self): gremmie@1: return self.image.url gremmie@1: gremmie@1: def html(self): bgneal@128: """Returns a HTML img tag representation of the smiley.""" gremmie@1: if self.image: bgneal@123: return (u'%s' % bgneal@123: (self.get_absolute_url(), self.title, self.title)) gremmie@1: return u'' gremmie@1: html.allow_tags = True gremmie@1: bgneal@128: def markdown(self): bgneal@128: """Returns a markdown representation of the smiley.""" bgneal@128: if self.image: bgneal@128: return (u'![%s](%s "%s")' % bgneal@128: (self.title, self.get_absolute_url(), self.title)) bgneal@128: return u''