Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Specifying default attr for Custom widget

I have created this widget

class DateTimeWidget(forms.TextInput):
  attr = {'class': 'datetimepicker'}
  class Media:
    js = ('js/jquery-ui-timepicker-addon.js',)

Then I use it on my form

class SessionForm(forms.ModelForm):
  class Meta:
    model = Session
  def __init__(self, *args, **kwargs):
    super(SessionForm, self).__init__(*args, **kwargs)
    self.fields['start_time'].widget = DateTimeWidget()
    self.fields['end_time'].widget = DateTimeWidget()

No css class is applied to my fields (I'm expecting datetimepicker applied to both start_time & end_time).
I imagine I have put attr at a wrong location. Where am I supposed to specify it ?

like image 328
Pierre de LESPINAY Avatar asked Sep 20 '25 15:09

Pierre de LESPINAY


1 Answers

Firstly, the html attributes are stored in widget.attrs, not attr.

Secondly, you can't declare attrs = {'class': 'datetimepicker'} in your widget definition, because the __init__ method will overwrite self.attrs.

Instead, you can set the attrs in the __init__ method.

Here's a rather naive implementation. You might want to add some extra checks to make sure you don't overwrite any existing items in kwargs['attrs']. Note that we have subclassed DateTimeInput instead of TextInput.

class DateTimeWidget(DateTimeInput):
    def __init__(self, *args, **kwargs):
        kwargs['attrs'] = {'class': 'datepicker'}
        super(DatePickerWidget, self).__init__(*args, **kwargs)
like image 175
Alasdair Avatar answered Sep 22 '25 13:09

Alasdair