Show toolbar tooltips with access keys for buttons without description.
[redakcja.git] / src / cover / models.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from django.core.files.base import ContentFile
5 from django.core.files.storage import FileSystemStorage
6 from django.db import models
7 from django.db.models.signals import post_save
8 from django.dispatch import receiver
9 from django.urls import reverse
10 from django.utils.translation import ugettext_lazy as _
11 from django.contrib.sites.models import Site
12 from cover.utils import URLOpener
13
14
15 class OverwriteStorage(FileSystemStorage):
16
17     def get_available_name(self, name, max_length=None):
18         self.delete(name)
19         return name
20
21
22 class Image(models.Model):
23     title = models.CharField(max_length=255, verbose_name=_('title'))
24     author = models.CharField(max_length=255, verbose_name=_('author'))
25     license_name = models.CharField(max_length=255, verbose_name=_('license name'))
26     license_url = models.URLField(max_length=255, blank=True, verbose_name=_('license URL'))
27     source_url = models.URLField(verbose_name=_('source URL'), null=True, blank=True)
28     download_url = models.URLField(unique=True, verbose_name=_('image download URL'), null=True, blank=True)
29     file = models.ImageField(
30         upload_to='cover/image', storage=OverwriteStorage(), editable=True, verbose_name=_('file'))
31
32     class Meta:
33         verbose_name = _('cover image')
34         verbose_name_plural = _('cover images')
35
36     def __str__(self):
37         return u"%s - %s" % (self.author, self.title)
38
39     def get_absolute_url(self):
40         return reverse('cover_image', args=[self.id])
41
42     def get_full_url(self):
43         return "http://%s%s" % (Site.objects.get_current().domain, self.get_absolute_url())
44
45
46 @receiver(post_save, sender=Image)
47 def download_image(sender, instance, **kwargs):
48     if instance.pk and not instance.file:
49         t = URLOpener().open(instance.download_url).read()
50         instance.file.save("%d.jpg" % instance.pk, ContentFile(t))