Maybe adding `option_attrs` (either as class attribute or as `__init__`
parameter) could be a solution.
--
Ticket URL: <https://code.djangoproject.com/ticket/34034>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
Comment (by Mark Walker):
Could you add an example of the difficulty?
Looking at the `Select` widget
([https://github.com/django/django/blob/main/django/forms/widgets.py#L737
source]), it defines an attribute `multiple`;
{{{
#!div style="font-size: 80%"
Code highlighting:
{{{#!python
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
if self.allow_multiple_selected:
context["widget"]["attrs"]["multiple"] = True
return context
}}}
}}}
So I'm assuming this then renders with `<select multiple>`. If that's the
level you want to add a class to, `context["widget"]["attrs"]["class"] =
"my-select-class"` should then render your classes.
--
Ticket URL: <https://code.djangoproject.com/ticket/34034#comment:1>
Comment (by Claude Paroz):
That means that you have to subclass the Django widget. Then for
subwidgets, you have to override `create_option`, not `get_context`. Then
you have to take care not overwriting any existing class content. So in
some code of mine, I had to write:
{{{
def create_option(self, *args, attrs=None, **kwargs):
attrs = attrs.copy() if attrs else {}
if 'class' in attrs:
attrs['class'] += ' form-check-input'
else:
attrs.update({'class': 'form-check-input'})
return super().create_option(*args, attrs=attrs, **kwargs)
}}}
and note that the class name is hardcoded, so if you need another class
for another part of a form, you have to set the class name as a subclass
attribute, and create other widget subclasses. And as that can touch
`RadioSelect`, `CheckboxSelectMultiple`, etc., you'll have to create
subclasses for all of them (if used, of course).
That's what I mean by "excessingly difficult". But it's doable, of course.
--
Ticket URL: <https://code.djangoproject.com/ticket/34034#comment:2>