1 # -*- coding: utf-8 -*-
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from django import forms
7 from django.utils.translation import ugettext_lazy as _, ugettext
8 from cover.models import Image
9 from django.utils.text import mark_safe
11 from cover.utils import get_flickr_data, FlickrError
14 class ImageAddForm(forms.ModelForm):
18 def __init__(self, *args, **kwargs):
19 super(ImageAddForm, self).__init__(*args, **kwargs)
20 self.fields['file'].required = False
22 def clean_download_url(self):
23 cl = self.cleaned_data['download_url'] or None
26 img = Image.objects.get(download_url=cl)
27 except Image.DoesNotExist:
30 raise forms.ValidationError(mark_safe(
31 ugettext('Image <a href="%(url)s">already in repository</a>.')
32 % {'url': img.get_absolute_url()}))
36 cleaned_data = super(ImageAddForm, self).clean()
37 if not cleaned_data.get('download_url', None) and not cleaned_data.get('file', None):
38 raise forms.ValidationError('No image specified')
42 class ImageEditForm(forms.ModelForm):
43 """Form used for editing a Book."""
46 exclude = ['download_url']
49 class ReadonlyImageEditForm(ImageEditForm):
50 """Form used for not editing an Image."""
52 def __init__(self, *args, **kwargs):
53 super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
54 for field in self.fields.values():
55 field.widget.attrs.update({"readonly": True})
57 def save(self, *args, **kwargs):
58 raise AssertionError("ReadonlyImageEditForm should not be saved.")
61 class FlickrForm(forms.Form):
62 source_url = forms.URLField(label=_('Flickr URL'))
64 def clean_source_url(self):
65 url = self.cleaned_data['source_url']
67 flickr_data = get_flickr_data(url)
68 except FlickrError as e:
69 raise forms.ValidationError(e)
70 for field_name in ('license_url', 'license_name', 'author', 'title', 'download_url'):
71 self.cleaned_data[field_name] = flickr_data[field_name]
72 return flickr_data['source_url']