How to properly set default value of a DateField to today’s date in FlaskForm

This is a small problem I hit while building a Flask-powered website. I have a form that allows a user to enter a date to retrieve records from the database.

The original code looks like this:

class FilterForm(FlaskForm):
    mydate = DateField('End Date', format='%Y-%m-%d', validators=[DataRequired()], 
                        default=datetime.now(pytz.timezone('US/Pacific')))

The problem with this code, however, is the default value is evaluated only once when Flask is brought up. So it seems to work the day this website is deployed, but afterwards the default date never changes.

Obviously this is wrong. What we need is a way to provide the current time to the form when the form is generated. To do so, we remove the default value from the field description, and provides the value in initialization instead.

class FilterForm(FlaskForm):
    mydate = DateField('End Date', format='%Y-%m-%d', validators=[DataRequired()])

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not self.mydate.data:
            self.mydate.data = datetime.now(pytz.timezone('US/Pacific'))

Leave a ReplyCancel reply