Django and date range picker component for Twitter Bootstrap

妖精的绣舞 提交于 2019-12-06 07:43:30

I had to do this; so I share the code here. It basically re-uses Django DateField.

class DateRangeField(forms.DateField):
    def to_python(self, value):
        values = value.split(' - ')
        from_date = super(DateRangeField, self).to_python(values[0])
        to_date = super(DateRangeField, self).to_python(values[1])
        return from_date, to_date

and

date_range = DateRangeField(required=False,
                            widget=forms.TextInput(attrs={'placeholder': _('from'),
                                                          'class': 'form-control datepicker'}))

Given that the example output is

MM/DD/YYYY - MM/DD/YYYY

This is what will post to your view. I would just handle this on your own rather than using a Django Form, and store it in two DateFields. Something along the lines of this:

date_range = request.POST['date_range']
start_date_string = date_range.split(' - ')[0]
end_date_string = date.range.split(' - ')[1]

This will get you your two strings needed, then simply just pass them into the DateFields and save it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!