Skip to content

Commit 6eec7d4

Browse files
committed
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.
1 parent 4e77896 commit 6eec7d4

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

sorl/thumbnail/fields.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from django.db.models import Q
33
from django import forms
44
from django.utils.translation import gettext_lazy as _
5+
from django.forms.widgets import FileInput
56

67
from sorl.thumbnail import default
78

@@ -68,3 +69,9 @@ def to_python(self, data):
6869
f.seek(0)
6970

7071
return f
72+
73+
def widget_attrs(self, widget):
74+
attrs = super().widget_attrs(widget)
75+
if isinstance(widget, FileInput) and 'accept' not in widget.attrs:
76+
attrs.setdefault('accept', 'image/*')
77+
return attrs
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from django import forms
2+
from django.test import SimpleTestCase
3+
from django.forms.widgets import FileInput
4+
5+
from sorl.thumbnail.fields import ImageFormField
6+
7+
8+
class ImageFormFieldTest(SimpleTestCase):
9+
10+
def assertWidgetRendersTo(self, field, to):
11+
class Form(forms.Form):
12+
f = field
13+
self.assertHTMLEqual(str(Form()["f"]), to)
14+
15+
def test_widget_attrs_default_accept(self):
16+
f = ImageFormField()
17+
self.assertEqual(f.widget_attrs(FileInput()), {'accept': 'image/*'})
18+
self.assertWidgetRendersTo(f, '<input type="file" name="f" accept="image/*" required id="id_f" />')

0 commit comments

Comments
 (0)