Skip to content

Commit eb17128

Browse files
authored
Make ImageFormField render with accept="image/*"' HTML attribute (#731)
Since Django 2.1, the default forms.ImageField has rendered with accept="image/*". Copy the code here to do the same.
1 parent bab6bb5 commit eb17128

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
@@ -1,6 +1,7 @@
11
from django import forms
22
from django.db import models
33
from django.utils.translation import gettext_lazy as _
4+
from django.forms.widgets import FileInput
45

56
from sorl.thumbnail import default
67

@@ -48,3 +49,9 @@ def to_python(self, data):
4849
f.seek(0)
4950

5051
return f
52+
53+
def widget_attrs(self, widget):
54+
attrs = super().widget_attrs(widget)
55+
if isinstance(widget, FileInput) and 'accept' not in widget.attrs:
56+
attrs.setdefault('accept', 'image/*')
57+
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)