From 5e65d569bf9c0f92aa98fba694b719c36f50128d Mon Sep 17 00:00:00 2001 From: TAKAHASHI Shuuji Date: Mon, 16 Jan 2023 02:29:18 +0900 Subject: [PATCH] Prevent uploading too large image file (#416) --- activities/views/compose.py | 29 +++++++++++++++++++++++-- static/css/style.css | 1 + templates/activities/_image_upload.html | 2 +- 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/activities/views/compose.py b/activities/views/compose.py index 827b105..8d8ef96 100644 --- a/activities/views/compose.py +++ b/activities/views/compose.py @@ -204,7 +204,30 @@ class ImageUpload(FormView): template_name = "activities/_image_upload.html" class form_class(forms.Form): - image = forms.ImageField() + image = forms.ImageField( + widget=forms.FileInput( + attrs={ + "_": f""" + on change + if me.files[0].size > {settings.SETUP.MEDIA_MAX_IMAGE_FILESIZE_MB * 1024 ** 2} + add [@disabled=] to #upload + + remove + make called errorlist + make
  • called error + set size_in_mb to (me.files[0].size / 1024 / 1024).toFixed(2) + put 'File must be 10MB or less (actual: ' + size_in_mb + 'MB)' into error + put error into errorlist + put errorlist before me + else + remove @disabled from #upload + remove + end + end + """ + } + ) + ) description = forms.CharField(required=False) def clean_image(self): @@ -214,7 +237,9 @@ class ImageUpload(FormView): if value.size > max_bytes: # Erase the file from our data to stop trying to show it again self.files = {} - raise forms.ValidationError(f"File must be {max_mb}MB or less") + raise forms.ValidationError( + f"File must be {max_mb}MB or less (actual: {value.size / 1024 ** 2:.2f})" + ) return value def form_invalid(self, form): diff --git a/static/css/style.css b/static/css/style.css index 2888880..312a837 100644 --- a/static/css/style.css +++ b/static/css/style.css @@ -1034,6 +1034,7 @@ button.toggle, button[disabled], .button[disabled] { background: var(--color-button-disabled); + cursor: not-allowed; } button.left, diff --git a/templates/activities/_image_upload.html b/templates/activities/_image_upload.html index c812c44..dec9160 100644 --- a/templates/activities/_image_upload.html +++ b/templates/activities/_image_upload.html @@ -9,7 +9,7 @@ {% include "forms/_field.html" with field=form.image %} {% include "forms/_field.html" with field=form.description %}
    - +