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.
6 from django import forms
7 from django.conf import settings
8 from django.utils.translation import ugettext_lazy as _, ugettext
9 from cover.models import Image
10 from django.utils.safestring import mark_safe
11 from PIL import Image as PILImage
13 from cover.utils import get_import_data, FlickrError, URLOpener
16 class ImageAddForm(forms.ModelForm):
21 def __init__(self, *args, **kwargs):
22 super(ImageAddForm, self).__init__(*args, **kwargs)
23 self.fields['file'].required = False
24 self.fields['use_file'].required = False
25 self.fields['cut_top'].required = False
26 self.fields['cut_left'].required = False
27 self.fields['cut_bottom'].required = False
28 self.fields['cut_right'].required = False
30 def clean_download_url(self):
31 cl = self.cleaned_data['download_url'] or None
34 img = Image.objects.get(download_url=cl)
35 except Image.DoesNotExist:
38 raise forms.ValidationError(mark_safe(
39 ugettext('Image <a href="%(url)s">already in repository</a>.')
40 % {'url': img.get_absolute_url()}))
43 def clean_source_url(self):
44 source_url = self.cleaned_data['source_url'] or None
45 if source_url is not None:
46 same_source = Image.objects.filter(source_url=source_url)
48 raise forms.ValidationError(mark_safe(
49 ugettext('Image <a href="%(url)s">already in repository</a>.')
50 % {'url': same_source.first().get_absolute_url()}))
53 clean_cut_top = lambda self: self.cleaned_data.get('cut_top') or 0
54 clean_cut_bottom = lambda self: self.cleaned_data.get('cut_bottom') or 0
55 clean_cut_left = lambda self: self.cleaned_data.get('cut_left') or 0
56 clean_cut_right = lambda self: self.cleaned_data.get('cut_right') or 0
59 cleaned_data = super(ImageAddForm, self).clean()
60 download_url = cleaned_data.get('download_url', None)
61 uploaded_file = cleaned_data.get('file', None)
62 if not download_url and not uploaded_file:
63 raise forms.ValidationError(ugettext('No image specified'))
65 image_data = URLOpener().open(download_url).read()
66 width, height = PILImage.open(BytesIO(image_data)).size
68 width, height = PILImage.open(uploaded_file.file).size
69 min_width, min_height = settings.MIN_COVER_SIZE
70 if width < min_width or height < min_height:
71 raise forms.ValidationError(ugettext('Image too small: %sx%s, minimal dimensions %sx%s') %
72 (width, height, min_width, min_height))
76 class ImageEditForm(forms.ModelForm):
77 """Form used for editing a Book."""
80 exclude = ['download_url']
83 cleaned_data = super(ImageEditForm, self).clean()
84 uploaded_file = cleaned_data.get('file', None)
85 width, height = PILImage.open(uploaded_file.file).size
86 min_width, min_height = settings.MIN_COVER_SIZE
87 if width < min_width or height < min_height:
88 raise forms.ValidationError(ugettext('Image too small: %sx%s, minimal dimensions %sx%s') %
89 (width, height, min_width, min_height))
92 class ReadonlyImageEditForm(ImageEditForm):
93 """Form used for not editing an Image."""
95 def __init__(self, *args, **kwargs):
96 super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
97 for field in self.fields.values():
98 field.widget.attrs.update({"readonly": True})
100 def save(self, *args, **kwargs):
101 raise AssertionError("ReadonlyImageEditForm should not be saved.")
104 class ImportForm(forms.Form):
105 source_url = forms.URLField(label=_('WikiCommons, MNW, Flickr, RawPixel URL'))
107 def clean_source_url(self):
108 url = self.cleaned_data['source_url']
110 import_data = get_import_data(url)
111 except FlickrError as e:
112 raise forms.ValidationError(e)
113 for field_name in ('license_url', 'license_name', 'author', 'title', 'download_url'):
114 self.cleaned_data[field_name] = import_data[field_name]
115 return import_data['source_url']