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 sorl.thumbnail.fields import ImageWithThumbnailsField
13 from sponsors.fields import JSONField
14 from django.core.files.base import ContentFile
19 class Sponsor(models.Model):
20 name = models.CharField(_('name'), max_length=120)
21 _description = models.CharField(_('description'), blank=True, max_length=255)
22 logo = ImageWithThumbnailsField(
24 upload_to='sponsorzy/sponsor/logo',
26 'size': (THUMB_WIDTH, THUMB_HEIGHT),
28 'options': ['pad', 'detail'],
30 url = models.URLField(_('url'), blank=True, verify_exists=False)
32 def __unicode__(self):
35 def description(self):
36 if len(self._description):
37 return self._description
42 class SponsorPage(models.Model):
43 name = models.CharField(_('name'), max_length=120)
44 sponsors = JSONField(_('sponsors'), default={})
45 _html = models.TextField(blank=True, editable=False)
46 sprite = models.ImageField(upload_to='sponsorzy/sprite', blank=True)
48 def populated_sponsors(self):
51 for column in self.get_sponsors_value():
52 result_group = {'name': column['name'], 'sponsors': []}
53 sponsor_objects = Sponsor.objects.in_bulk(column['sponsors'])
54 for sponsor_pk in column['sponsors']:
56 result_group['sponsors'].append((offset, sponsor_objects[sponsor_pk]))
57 offset -= THUMB_HEIGHT
60 result.append(result_group)
63 def render_sprite(self):
65 for column in self.get_sponsors_value():
66 sponsor_ids.extend(column['sponsors'])
67 sponsors = Sponsor.objects.in_bulk(sponsor_ids)
68 sprite = Image.new('RGB', (THUMB_WIDTH, len(sponsors)*THUMB_HEIGHT))
69 for i, sponsor_id in enumerate(sponsor_ids):
70 simg = Image.open(sponsors[sponsor_id].logo.thumbnail.dest)
71 sprite.paste(simg, (0, i*THUMB_HEIGHT))
73 sprite.save(imgstr, 'png')
76 self.sprite.delete(save=False)
77 self.sprite.save('sponsorzy/sprite/%s-%d.png' % (self.name, time.time()), ContentFile(imgstr.getvalue()), save=False)
81 html = property(fget=html)
83 def save(self, *args, **kwargs):
85 self._html = render_to_string('sponsors/page.html', {
86 'sponsors': self.populated_sponsors(),
89 return super(SponsorPage, self).save(*args, **kwargs)
91 def __unicode__(self):