Update file forms.py
This commit is contained in:
parent
e210a3262d
commit
88fd7a1ec0
1 changed files with 19 additions and 3 deletions
|
|
@ -16,8 +16,9 @@ from .models import Gallery, Tag
|
||||||
class MultipleFileInput(forms.ClearableFileInput):
|
class MultipleFileInput(forms.ClearableFileInput):
|
||||||
allow_multiple_selected = True
|
allow_multiple_selected = True
|
||||||
|
|
||||||
|
|
||||||
class MultipleFileField(forms.FileField):
|
class MultipleFileField(forms.FileField):
|
||||||
|
allowed_extensions = ['jpg', 'jpeg', 'png','gif', 'tiff'] # Specify allowed extensions here
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
kwargs.setdefault(
|
kwargs.setdefault(
|
||||||
"widget",
|
"widget",
|
||||||
|
|
@ -32,12 +33,27 @@ class MultipleFileField(forms.FileField):
|
||||||
|
|
||||||
def clean(self, data, initial=None):
|
def clean(self, data, initial=None):
|
||||||
single_file_clean = super().clean
|
single_file_clean = super().clean
|
||||||
|
|
||||||
if isinstance(data, (list, tuple)):
|
if isinstance(data, (list, tuple)):
|
||||||
result = [single_file_clean(d, initial) for d in data]
|
result = [self.validate_file(d, single_file_clean, initial) for d in data]
|
||||||
else:
|
else:
|
||||||
result = single_file_clean(data, initial)
|
result = self.validate_file(data, single_file_clean, initial)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
def validate_file(self, file, single_file_clean, initial):
|
||||||
|
# Perform the default clean
|
||||||
|
cleaned_file = single_file_clean(file, initial)
|
||||||
|
|
||||||
|
# Check the file extension
|
||||||
|
extension = file.name.split('.')[-1].lower()
|
||||||
|
if extension not in self.allowed_extensions:
|
||||||
|
raise forms.ValidationError(
|
||||||
|
f"{file.name} has an invalid file extension. "
|
||||||
|
f"Allowed extensions are: {', '.join(self.allowed_extensions)}"
|
||||||
|
)
|
||||||
|
return cleaned_file
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class UploadForm(forms.Form):
|
class UploadForm(forms.Form):
|
||||||
file_field = MultipleFileField(label="")
|
file_field = MultipleFileField(label="")
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue