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.
7 from StringIO import StringIO
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
20 class Sponsor(models.Model):
21 name = models.CharField(_('name'), max_length=120)
22 _description = models.CharField(_('description'), blank=True, max_length=255)
23 logo = models.ImageField(_('logo'), upload_to='sponsorzy/sponsor/logo')
24 url = models.URLField(_('url'), blank=True)
26 def __unicode__(self):
29 def description(self):
30 if len(self._description):
31 return self._description
36 class SponsorPage(models.Model):
37 name = models.CharField(_('name'), max_length=120)
38 sponsors = JSONField(_('sponsors'), default={})
39 _html = models.TextField(blank=True, editable=False)
40 sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
42 def populated_sponsors(self):
45 for column in self.sponsors:
46 result_group = {'name': column['name'], 'sponsors': []}
47 sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
48 for sponsor_pk in column['sponsors']:
50 result_group['sponsors'].append((offset, sponsor_objects[sponsor_pk]))
51 offset -= THUMB_HEIGHT
54 result.append(result_group)
57 def render_sprite(self):
59 for column in self.sponsors:
60 sponsor_ids.extend(column['sponsors'])
61 sponsors = Sponsor.objects.in_bulk(sponsor_ids)
62 sprite = Image.new('RGBA', (THUMB_WIDTH, len(sponsors) * THUMB_HEIGHT))
63 for i, sponsor_id in enumerate(sponsor_ids):
64 simg = Image.open(sponsors[sponsor_id].logo.path)
65 if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT:
68 simg.size[0] * THUMB_HEIGHT / simg.size[1]),
70 simg.size[1] * THUMB_WIDTH / simg.size[0])
72 simg = simg.resize(size, Image.ANTIALIAS)
74 (THUMB_WIDTH - simg.size[0]) / 2,
75 i * THUMB_HEIGHT + (THUMB_HEIGHT - simg.size[1]) / 2,
78 sprite.save(imgstr, 'png')
81 self.sprite.delete(save=False)
82 self.sprite.save('sponsorzy/sprite/%s-%d.png' % (self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
86 html = property(fget=html)
88 def save(self, *args, **kwargs):
89 if isinstance(self.sponsors, basestring):
90 # Walkaround for weird jsonfield 'no-decode' optimization.
91 self.sponsors = json.loads(self.sponsors)
93 self._html = render_to_string('sponsors/page.html', {
94 'sponsors': self.populated_sponsors(),
97 return super(SponsorPage, self).save(*args, **kwargs)
99 def __unicode__(self):