-
Notifications
You must be signed in to change notification settings - Fork 13
/
forms.py
37 lines (28 loc) · 1.21 KB
/
forms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import PIL
from django import forms
from PIL import Image
# Referring to https://docs.djangoproject.com/en/4.2/topics/http/file-uploads/#uploading-multiple-files
class MultipleFileInput(forms.ClearableFileInput):
allow_multiple_selected = True
class MultipleFileField(forms.FileField):
def __init__(self, *args, **kwargs):
kwargs.setdefault("widget", MultipleFileInput())
super().__init__(*args, **kwargs)
def clean(self, data, initial=None):
single_file_clean = super().clean
if data and isinstance(data, (list, tuple)):
result = [single_file_clean(d, initial) for d in data]
else:
result = single_file_clean(data, initial)
return result
def validate(self, value):
""" Validate file by checking it can be opened by PIL """
try:
Image.open(value)
except PIL.UnidentifiedImageError as e:
raise forms.ValidationError("Unable to add invalid image: %(name)s",
params={"name": value.name})
except AttributeError:
raise forms.ValidationError("Unable to add empty image")
class ImageCreateForm(forms.Form):
data = MultipleFileField()