Set flask wtform's default date as today

Issue

A basic flask wtform with 2 input dates and a submit button will be :

class WelcomeForm(FlaskForm):
startdate = DateField('Start Date', format='%Y-%m-%d',validators=(validators.DataRequired(),))
enddate = DateField('End Date', format='%Y-%m-%d',validators=(validators.DataRequired(),))
submit = SubmitField('Submit')

How do we set default dates for the form?

Note : This is only for date and not datetime.

Solution

This is the answer to my question, hope it helps others who are looking for it.

    from datetime import datetime, date, timedelta
    class WelcomeForm(FlaskForm):
    today = date.today()
    sevendaysago = date.today() - timedelta(days = 7)
    startdate = DateField('Start Date', format='%Y-%m-%d',default=sevendaysago,validators=(validators.DataRequired(),))
    enddate = DateField('End Date', format='%Y-%m-%d', default = today, validators=(validators.DataRequired(),))
    submit = SubmitField('Submit')

Answered By – Shravya Mutyapu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published