Dodanie sorl.thumbnail i generowanie miniaturek logo na potrzeby aplikacji sponsors.
[wolnelektury.git] / apps / sponsors / models.py
1 from django.db import models
2 from django.utils.translation import ugettext_lazy as _
3 from django.template.loader import render_to_string
4
5 from sorl.thumbnail.fields import ImageWithThumbnailsField
6 from sponsors.fields import JSONField
7
8
9 class Sponsor(models.Model):
10     name = models.CharField(_('name'), max_length=120)
11     _description = models.CharField(_('description'), blank=True, max_length=255)
12     logo = ImageWithThumbnailsField(
13         _('logo'),
14         upload_to='sponsors/sponsor/logo',
15         thumbnail={
16             'size': (150, 75),
17             'extension': 'png',
18             'options': ['upscale', 'pad', 'detail'],
19         })
20     url = models.URLField(_('url'), blank=True, verify_exists=False)
21     
22     def __unicode__(self):
23         return self.name
24
25     def description(self):
26         if len(self._description):
27             return self._description
28         else:
29             return self.name
30
31
32 class SponsorPage(models.Model):
33     name = models.CharField(_('name'), max_length=120)
34     column_width = models.PositiveIntegerField(_('column width'), default=200)
35     sponsors = JSONField(_('sponsors'), default={})
36     _html = models.TextField(blank=True, editable=False)
37     
38     def populated_sponsors(self):
39         result = []
40         for column in self.get_sponsors_value():
41             result_group = {'name': column['name'], 'sponsors': []}
42             sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
43             for sponsor_pk in column['sponsors']:
44                 try:
45                     result_group['sponsors'].append(sponsor_objects[sponsor_pk])
46                 except KeyError:
47                     pass
48             result.append(result_group)
49         return result
50     
51     def html(self):
52         return self._html
53     html = property(fget=html)
54
55     def save(self, *args, **kwargs):
56         self._html = render_to_string('sponsors/page.html', {
57             'column_width': self.column_width,
58             'sponsors': self.populated_sponsors(),
59         })
60         return super(SponsorPage, self).save(*args, **kwargs)
61     
62     def __unicode__(self):
63         return self.name
64