Can I limit the dates possibilities using django widget DateInput, ex. between 2020-01-01 and 2023-12-31

Viewed 892

Using the widget DateInput, I would like to limit the range of dates offered by the datepicker to a set range, for example between Jan. 1, 2020 to Dec. 31, 2023.

I understand, that the date could be validated after it has been entered but is it possible to limit what the user could enter.

1 Answers

Yes it's possible. Have a look at the docs here and the example below.

class CommentForm(forms.Form):
    name = forms.DateField(widget=forms.DateField(attrs={'min': '2020-01-01', 'max': '2021-01-01'}))

Or in the __init__:

self.fields['name'].widget.attrs.update({'min': '2020-01-01', 'max': '2021-01-01'})

You might want to use a datepicker made by someone else since the HTML5 datepicker might not show on IE or Safari.

Related