Home > Software design >  Django SelectDateWidget
Django SelectDateWidget

Time:12-28

date_range = 100    
this_year = date.today().year
birth_date= forms.DateField(label='What is your birth date?', widget=forms.SelectDateWidget(years=range(this_year - date_range, this_year 1)))

I would like to only select dates 100 years from today. But I currently can get values like Dec 31 2021 where sometimes the months and days don't match the correct values.

CodePudding user response:

Django expects a list or tuple for years parameter in SelectDateWidget. Try with:

this_year = date.today().year
year_range = [x for x in range(this_year - 100, this_year   1)]
birth_date = forms.DateField(
    label="What is your birth date?",
    widget=forms.SelectDateWidget(years=year_range),
)

Add a form field validator if you would like to check for a selected date within a specific range. Here's an example with a naive 100 years back calculation:

from datetime import datetime, timedelta

class YourForm():
    ...

    def clean_birth_date(self):
        birth_date = self.cleaned_data['birth_date']

        today = datetime.today()
        first_date = today - timedelta(days=100 * 365)

        if not (first_date < birth_date < today):
            raise ValidationError("Please select a date within the last 100 years")

        return data
  • Related