From 88fd7a1ec04b6f93061b4597fb3aef260f315704 Mon Sep 17 00:00:00 2001 From: parping Date: Tue, 19 Nov 2024 10:58:52 +0100 Subject: [PATCH] Update file forms.py --- photologue/forms.py | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/photologue/forms.py b/photologue/forms.py index 3749704..1fcdb7d 100644 --- a/photologue/forms.py +++ b/photologue/forms.py @@ -16,8 +16,9 @@ from .models import Gallery, Tag class MultipleFileInput(forms.ClearableFileInput): allow_multiple_selected = True - class MultipleFileField(forms.FileField): + allowed_extensions = ['jpg', 'jpeg', 'png','gif', 'tiff'] # Specify allowed extensions here + def __init__(self, *args, **kwargs): kwargs.setdefault( "widget", @@ -32,12 +33,27 @@ class MultipleFileField(forms.FileField): def clean(self, data, initial=None): single_file_clean = super().clean + 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: - result = single_file_clean(data, initial) + result = self.validate_file(data, single_file_clean, initial) 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): file_field = MultipleFileField(label="")