0

I would like to apply CSS to form.ImageFiled in Django same as Charfeild but I got the error.

  File "/Users/hogehoge/Desktop/hoge/hoge/forms.py", line 42, in PostForm
    photo = forms.ImageField(label='Image', validators=[file_size],widget=forms.ImageField(attrs={'class': 'fileinput'}))
  File "/Users/hoge/opt/anaconda3/lib/python3.8/site-packages/django/forms/fields.py", line 545, in __init__
    super().__init__(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'attrs'

How can I apply CSS CSS on form.ImageFiled?

forms.py

photo = forms.ImageField(label='Image', validators=[file_size],widget=forms.ImageField(attrs={'class': 'fileinput'}))

html

<div class="col-8 col-lg-4">{{ form.photo }}</div>

enter image description here

2 Answers 2

1

You are using the ImageField as a Widget class instead of a FileInput or ClearableFileInput.

Perhaps this will work:

photo = forms.ImageField(label='Image', validators=[file_size],widget=forms.ClearableFileInput(attrs={'class': 'fileinput'}))
0

HTML

{% load widget_tweaks %}
    .
    .
    .
        <div>
          <label for="id_photo" class="filelabel">ファイルを添付</label>
          <div class="col-8 col-lg-4">{{ form.photo|add_class:"fileinput" }} 
          </div>
        </div>

settings.py

INSTALLED_APPS = [
.
.
.

    'widget_tweaks',
]

I succeeded this code.