Drobne poprawki w aplikacje 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': (120, 60),
17             'extension': 'png',
18             'options': ['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     sponsors = JSONField(_('sponsors'), default={})
35     _html = models.TextField(blank=True, editable=False)
36     
37     def populated_sponsors(self):
38         result = []
39         for column in self.get_sponsors_value():
40             result_group = {'name': column['name'], 'sponsors': []}
41             sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
42             for sponsor_pk in column['sponsors']:
43                 try:
44                     result_group['sponsors'].append(sponsor_objects[sponsor_pk])
45                 except KeyError:
46                     pass
47             result.append(result_group)
48         return result
49     
50     def html(self):
51         return self._html
52     html = property(fget=html)
53
54     def save(self, *args, **kwargs):
55         self._html = render_to_string('sponsors/page.html', {
56             'column_width': self.column_width,
57             'sponsors': self.populated_sponsors(),
58         })
59         return super(SponsorPage, self).save(*args, **kwargs)
60     
61     def __unicode__(self):
62         return self.name
63