Search code examples
djangodjango-formsdjango-widget

selectdatewidget set default month and day


How can I set selectDateWidget day and month options to default as 1st January but leave the year option intact.

Now I am doing:

day = datetime.date.today()
lessTime = forms.DateField(required=False, widget=SelectDateWidget(years=range(1980, 2013)), initial=day)

But this sets the default to the actual date. What can I change to give me the desired default options?

Thanks in advance


Solution

  • Make a custom widget e.g MySelectDateWidget

    class MySelectDateWidget(SelectDateWidget):
        def render(self, name, value, attrs=None):
            from collections import namedtuple
            date_tweak = namedtuple('Date', 'year month day')
            date_value = date_tweak(None, 1, 1) #tweak to cheat SelectDateWidget's 
                                       #render method which expects a datetime object
            return super(MySelectDateWidget, self).render(name, date_value, attrs)
    

    and then replace:

    lessTime = forms.DateField(required=False,    
              widget=SelectDateWidget(years=range(1980, 2013)), initial=day)
    

    with:

    lessTime = forms.DateField(required=False,          
                               widget=MySelectDateWidget(years=range(1980, 2013)))