From 6eec7d48988e8aaa2eee08c058bf5e7eed10c124 Mon Sep 17 00:00:00 2001 From: Ryan Nowakowski Date: Sun, 7 May 2023 16:27:47 -0500 Subject: [PATCH] Make ImageFormField render with accept="image/*"' HTML attribute Since Django 2.1, the default forms.ImageField has rendered with accept="image/*". Copy the code here to do the same. --- sorl/thumbnail/fields.py | 7 +++++++ tests/thumbnail_tests/test_formfields.py | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 tests/thumbnail_tests/test_formfields.py diff --git a/sorl/thumbnail/fields.py b/sorl/thumbnail/fields.py index 4777864ea..65b6b12e6 100644 --- a/sorl/thumbnail/fields.py +++ b/sorl/thumbnail/fields.py @@ -2,6 +2,7 @@ from django.db.models import Q from django import forms from django.utils.translation import gettext_lazy as _ +from django.forms.widgets import FileInput from sorl.thumbnail import default @@ -68,3 +69,9 @@ def to_python(self, data): f.seek(0) return f + + def widget_attrs(self, widget): + attrs = super().widget_attrs(widget) + if isinstance(widget, FileInput) and 'accept' not in widget.attrs: + attrs.setdefault('accept', 'image/*') + return attrs diff --git a/tests/thumbnail_tests/test_formfields.py b/tests/thumbnail_tests/test_formfields.py new file mode 100644 index 000000000..b57c457bd --- /dev/null +++ b/tests/thumbnail_tests/test_formfields.py @@ -0,0 +1,18 @@ +from django import forms +from django.test import SimpleTestCase +from django.forms.widgets import FileInput + +from sorl.thumbnail.fields import ImageFormField + + +class ImageFormFieldTest(SimpleTestCase): + + def assertWidgetRendersTo(self, field, to): + class Form(forms.Form): + f = field + self.assertHTMLEqual(str(Form()["f"]), to) + + def test_widget_attrs_default_accept(self): + f = ImageFormField() + self.assertEqual(f.widget_attrs(FileInput()), {'accept': 'image/*'}) + self.assertWidgetRendersTo(f, '')