Forums

Wrong DateRange in validator

I am having problems with the following code in my form class.

date = DateField(u'Date', validators=[DataRequired(),
                    DateRange(max=date.today(), min=(date.today() - timedelta(days=7)))])

It is a flask app, using flask-wtf, wtf-components(for DateRange). date is part of a form for time submission and I am trying to limit the time entry to the last seven days. When I submit the form, it doesn't validate and I get a message below the input saying "Date must be between 2016-09-24 and 2016-10-01."
It seems like the date is a few days behind todays date. I thought it may be a problem with the form creation being cached somehow? I then reloaded the web app and it the form submission worked. Anyone know what may be going on here?

I'm not an expert on Flask-WTF specifically, but I think what's happening is that the code you quote above is being run when your website is started up, so the max and min values for the field will be fixed to the ones they take on at that point in time.

This Stack Overflow post has what looks like a good solution -- instead of specifying the validators when you define the field in your form class, you define a new method on the form class, which sets the validators on the field when it's called. Then you use the new method to create the form rather than using its normal constructor.

Thanks in Giles that makes perfect sense. Added the daterange validator in the new method, and in the view instead of form = MyForm() I did form = MyForm.new().