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.
8 from django.db import models
9 from django.utils.translation import ugettext_lazy as _
10 from django.template.loader import render_to_string
13 from jsonfield import JSONField
14 from django.core.files.base import ContentFile
15 from ssify import flush_ssi_includes
21 class Sponsor(models.Model):
22 name = models.CharField(_('name'), max_length=120)
23 _description = models.CharField(_('description'), blank=True, max_length=255)
24 logo = models.ImageField(_('logo'), upload_to='sponsorzy/sponsor/logo')
25 url = models.URLField(_('url'), blank=True)
30 def description(self):
31 if len(self._description):
32 return self._description
37 class SponsorPage(models.Model):
38 name = models.CharField(_('name'), max_length=120)
39 sponsors = JSONField(_('sponsors'), default={})
40 _html = models.TextField(blank=True, editable=False)
41 sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
43 def populated_sponsors(self):
46 for column in self.sponsors:
47 result_group = {'name': column['name'], 'sponsors': []}
48 sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
49 for sponsor_pk in column['sponsors']:
51 result_group['sponsors'].append((offset, sponsor_objects[sponsor_pk]))
52 offset -= THUMB_HEIGHT
55 result.append(result_group)
58 def render_sprite(self):
60 for column in self.sponsors:
61 sponsor_ids.extend(column['sponsors'])
62 sponsors = Sponsor.objects.in_bulk(sponsor_ids)
63 sprite = Image.new('RGBA', (THUMB_WIDTH, len(sponsors) * THUMB_HEIGHT))
64 for i, sponsor_id in enumerate(sponsor_ids):
65 simg = Image.open(sponsors[sponsor_id].logo.path)
66 if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT:
69 simg.size[0] * THUMB_HEIGHT / simg.size[1]),
71 simg.size[1] * THUMB_WIDTH / simg.size[0])
73 simg = simg.resize(size, Image.ANTIALIAS)
75 (THUMB_WIDTH - simg.size[0]) / 2,
76 i * THUMB_HEIGHT + (THUMB_HEIGHT - simg.size[1]) / 2,
79 sprite.save(imgstr, 'png')
82 self.sprite.delete(save=False)
83 self.sprite.save('sponsorzy/sprite/%s-%d.png' % (
84 self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
88 html = property(fget=html)
90 def save(self, *args, **kwargs):
91 if isinstance(self.sponsors, str):
92 # Walkaround for weird jsonfield 'no-decode' optimization.
93 self.sponsors = json.loads(self.sponsors)
95 self._html = render_to_string('sponsors/page.html', {
96 'sponsors': self.populated_sponsors(),
99 ret = super(SponsorPage, self).save(*args, **kwargs)
100 self.flush_includes()
103 def flush_includes(self):
104 flush_ssi_includes(['/sponsors/page/%s.html' % self.name])