In a Form I want to modify the widget of a field, like
"field": django.forms.CheckboxSelectMultiple(
attrs={
"id": "my-id",
"class": "foo"
"hx-get": "/some/path/,
"hx-target": "#target-id",
"hx-trigger": "load",
}
)
but it just renders
<div id="my-id" class="foo">...</div>
instead of
<div id="my-id" class="foo" hx-get="...", hx-target="...", "hx-trigger="...">...</div>
The reason seams to be, that the django/forms/widets/multiple_input.html renders only id and class
{% with id=widget.attrs.id %}<div{% if id %} id="{{ id }}"{% endif %}{% if widget.attrs.class %} class="{{ widget.attrs.class }}"{% endif %}>{% for group, options, index in widget.optgroups %}{% if group %}
Is there any knowledge, why the attrs
restricted to id
and class
?
Best regards
Firstly it’s important to note that the attrs
are primarily for the form elements. They’re not restricted to just “id” and “class”; if you inspect your html you’ll find that all of your checkboxes will likely have your hx-*
attributes.
For this particular widget it was decided that id
& class
are also used (note the id
on the checkboxes will have a different value) on the containing div. There’s probably a very good reason to keep this as the default behaviour, which someone else will be able to answer.
If you want to change the default behaviour it’s very simple - you can copy the template to your app with the same path in your templates/
directory - then modify it to use all attributes. You can do a similar thing with checkbox & friends if you want to keep the hx-* attributes out of them.
OK … I understand, the attrs
key does not change the selection
but the option
tags … this is unfortunate.
If you want to change the default behaviour it’s very simple - you can copy the template to your app with the same path in your templates/
directory - then modify it to use all attributes. You can do a similar thing with checkbox & friends if you want to keep the hx-* attributes out of them.
But this means, I would change the behavior of every multi-input widget.
Maybe I will try to implement a custom widget.