2

如何将 selectDateWidget 日期和月份选项设置为默认为 1 月 1 日,但保留年份选项不变。

现在我在做:

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

但这会将默认设置为实际日期。我可以改变什么来给我想要的默认选项?

提前致谢

4

1 回答 1

1

制作一个自定义小部件,例如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)

然后替换:

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

和:

lessTime = forms.DateField(required=False,          
                           widget=MySelectDateWidget(years=range(1980, 2013)))
于 2012-09-20T21:20:11.883 回答