Handle some deprecations
[redakcja.git] / src / cover / forms.py
index 7a85594..b7fddfb 100644 (file)
@@ -2,7 +2,7 @@
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
 from io import BytesIO
-
+from urllib.request import urlopen
 from django import forms
 from django.conf import settings
 from django.utils.translation import gettext_lazy as _, gettext
@@ -10,7 +10,7 @@ from cover.models import Image
 from django.utils.safestring import mark_safe
 from PIL import Image as PILImage
 
-from cover.utils import get_import_data, FlickrError, URLOpener
+from cover.utils import get_import_data, FlickrError
 
 
 class ImageAddForm(forms.ModelForm):
@@ -62,7 +62,8 @@ class ImageAddForm(forms.ModelForm):
         if not download_url and not uploaded_file:
             raise forms.ValidationError(gettext('No image specified'))
         if download_url:
-            image_data = URLOpener().open(download_url).read()
+            with urlopen(download_url) as f:
+                image_data = f.read()
             width, height = PILImage.open(BytesIO(image_data)).size
         else:
             width, height = PILImage.open(uploaded_file.file).size
@@ -77,16 +78,21 @@ class ImageEditForm(forms.ModelForm):
     """Form used for editing a Book."""
     class Meta:
         model = Image
-        exclude = ['download_url']
+        exclude = ['download_url', 'use_file', 'example',]
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.fields['file'].required = False
 
     def clean(self):
         cleaned_data = super(ImageEditForm, self).clean()
         uploaded_file = cleaned_data.get('file', None)
-        width, height = PILImage.open(uploaded_file.file).size
-        min_width, min_height = settings.MIN_COVER_SIZE
-        if width < min_width or height < min_height:
-            raise forms.ValidationError(gettext('Image too small: %sx%s, minimal dimensions %sx%s') %
-                                        (width, height, min_width, min_height))
+        if uploaded_file is not None:
+            width, height = PILImage.open(uploaded_file.file).size
+            min_width, min_height = settings.MIN_COVER_SIZE
+            if width < min_width or height < min_height:
+                raise forms.ValidationError(gettext('Image too small: %sx%s, minimal dimensions %sx%s') %
+                                            (width, height, min_width, min_height))
 
 
 class ReadonlyImageEditForm(ImageEditForm):