Skip to content

Commit

Permalink
Make ImageFormField render with accept="image/*"' HTML attribute
Browse files Browse the repository at this point in the history
Since Django 2.1, the default forms.ImageField has rendered with
accept="image/*".  Copy the code here to do the same.
  • Loading branch information
tubaman committed Oct 1, 2023
1 parent 4e77896 commit 6eec7d4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
7 changes: 7 additions & 0 deletions sorl/thumbnail/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
18 changes: 18 additions & 0 deletions tests/thumbnail_tests/test_formfields.py
Original file line number Diff line number Diff line change
@@ -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, '<input type="file" name="f" accept="image/*" required id="id_f" />')

0 comments on commit 6eec7d4

Please sign in to comment.