refreshing flickr cover images + some cleanup
[redakcja.git] / apps / cover / forms.py
1 # -*- coding: utf-8 -*-
2 #
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.
5 #
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
10
11 from cover.utils import get_flickr_data, FlickrError
12
13
14 class ImageAddForm(forms.ModelForm):
15     class Meta:
16         model = Image
17
18     def __init__(self, *args, **kwargs):
19         super(ImageAddForm, self).__init__(*args, **kwargs)
20         self.fields['file'].required = False
21
22     def clean_download_url(self):
23         cl = self.cleaned_data['download_url'] or None
24         if cl is not None:
25             try:
26                 img = Image.objects.get(download_url=cl)
27             except Image.DoesNotExist:
28                 pass
29             else:
30                 raise forms.ValidationError(mark_safe(
31                     ugettext('Image <a href="%(url)s">already in repository</a>.')
32                     % {'url': img.get_absolute_url()}))
33         return cl
34
35     def clean(self):
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')
39         return cleaned_data
40
41
42 class ImageEditForm(forms.ModelForm):
43     """Form used for editing a Book."""
44     class Meta:
45         model = Image
46         exclude = ['download_url']
47
48
49 class ReadonlyImageEditForm(ImageEditForm):
50     """Form used for not editing an Image."""
51
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})
56
57     def save(self, *args, **kwargs):
58         raise AssertionError("ReadonlyImageEditForm should not be saved.")
59
60
61 class FlickrForm(forms.Form):
62     source_url = forms.URLField(label=_('Flickr URL'))
63
64     def clean_source_url(self):
65         url = self.cleaned_data['source_url']
66         try:
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']