3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CheckboxSelectMultipleを使うとinput:clicked + labelが効かなくなる/

Last updated at Posted at 2020-03-14

Djangoのフォームフィールドでwidget引数にCheckboxSelectMultipleを設定すると、テンプレートで複数選択可能なtype=checkboxのinputを生成してくれます。

forms.py

class ExampleForm(forms.ModelForm):
    choice = forms.ModelMultipleChoiceField(required=False, queryset=ChoiceTag.objects, widget=forms.CheckboxSelectMultiple)
    class Meta:
        model = Example
        fields = ['choice']

views.py

from .forms import ExampleForm
...
class ProfileEdit(LoginRequiredMixin, CreateView):
    def post(self, request, *args, **kwargs):
        form = ExampleForm()
        return render(request, "app/index.html", { "form" : form })

template(index.html)

{{ form.choice }}

html

<ul>
 <li>
   <label for="id_example">
     <input type="checkbox" name="example" id="id_example">
   </label>
 </li>
  ...
</ul>

\すごく簡単/

でもlabelの中にinputが入ってしまってlnput:clicked + labelが効かなくなってしまいます。

そんな時は{{ form.choice }}部分のテンプレートを以下のように修正してみてください。

<ul>
{% for i in form.choice %}
  <li>
    {{ i.tag }}
    <label for="{{ i.id_for_label }}">{{ i.choice_label }}</label>
  </il>
{% endfor %}
</ul>

{{ i.tag }}部分にinputのタグが、{ i.id_for_label }}にinputのid名が、{{ i.choice_label }}にそれぞれの選択肢の名前が入ります。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?