0

I've defined the following custom widget in forms.py, which over rides the standard HTML to create a "live search" select menu (user can enter free text to search options, useful when there are many options). For this widget to work, the class="selectpicker" class must be applied. How do I apply this class at the widget level?

class LiveSelectWidget(forms.widgets.Select):
template_name = "widgets/live_select.html"
option_template_name = 'widgets/live_select_option.html'
rcx935
  • 217
  • 5
  • 15
  • there 2 ways, when you specify the widget in your form field you can add `attrs` like so `forms.CharField(widget= LiveSelectWidget(attrs={'class': 'selectpicker'}))`. Another way is writing the class directly within your `widgets/live_select.html`. You can look more into it in the docs https://docs.djangoproject.com/en/3.2/ref/forms/widgets/#styling-widget-instances – Linh Nguyen Nov 03 '21 at 07:13
  • @LinhNguyen any way to add the class in the widget definition? Adding the class to each field doesn't sound right as the class should always be applied to the widget. I'm not sure about adding it to the HTML as the class is added into that using an include that's out of my control: – rcx935 Nov 03 '21 at 07:17
  • i found this neat way of specify default attribute for custom widget https://stackoverflow.com/a/9908085/11225821 . This probably is what you looking for – Linh Nguyen Nov 03 '21 at 07:20

0 Answers0