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.
6 from StringIO import StringIO
7 from django.db import models
8 from django.utils.translation import ugettext_lazy as _
9 from django.template.loader import render_to_string
12 from sponsors.fields import JSONField
13 from django.core.files.base import ContentFile
18 class Sponsor(models.Model):
19 name = models.CharField(_('name'), max_length=120)
20 _description = models.CharField(_('description'), blank=True, max_length=255)
21 logo = models.ImageField(_('logo'), upload_to='sponsorzy/sponsor/logo')
22 url = models.URLField(_('url'), blank=True, verify_exists=False)
24 def __unicode__(self):
27 def description(self):
28 if len(self._description):
29 return self._description
34 class SponsorPage(models.Model):
35 name = models.CharField(_('name'), max_length=120)
36 sponsors = JSONField(_('sponsors'), default={})
37 _html = models.TextField(blank=True, editable=False)
38 sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
40 def populated_sponsors(self):
43 for column in self.get_sponsors_value():
44 result_group = {'name': column['name'], 'sponsors': []}
45 sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
46 for sponsor_pk in column['sponsors']:
48 result_group['sponsors'].append((offset, sponsor_objects[sponsor_pk]))
49 offset -= THUMB_HEIGHT
52 result.append(result_group)
55 def render_sprite(self):
57 for column in self.get_sponsors_value():
58 sponsor_ids.extend(column['sponsors'])
59 sponsors = Sponsor.objects.in_bulk(sponsor_ids)
60 sprite = Image.new('RGBA', (THUMB_WIDTH, len(sponsors)*THUMB_HEIGHT))
61 for i, sponsor_id in enumerate(sponsor_ids):
62 simg = Image.open(sponsors[sponsor_id].logo.path)
63 if simg.size[0] > THUMB_WIDTH or simg.size[1] > THUMB_HEIGHT:
66 simg.size[0] * THUMB_HEIGHT / simg.size[1]),
68 simg.size[1] * THUMB_WIDTH / simg.size[0])
70 simg = simg.resize(size, Image.ANTIALIAS)
72 (THUMB_WIDTH - simg.size[0]) / 2,
73 i * THUMB_HEIGHT + (THUMB_HEIGHT - simg.size[1]) / 2,
76 sprite.save(imgstr, 'png')
79 self.sprite.delete(save=False)
80 self.sprite.save('sponsorzy/sprite/%s-%d.png' % (self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
84 html = property(fget=html)
86 def save(self, *args, **kwargs):
88 self._html = render_to_string('sponsors/page.html', {
89 'sponsors': self.populated_sponsors(),
92 return super(SponsorPage, self).save(*args, **kwargs)
94 def __unicode__(self):