wtforms+flask today's date as a default value
Asked Answered
P

2

14

I did a small Flask app with a form with two date fields, and this is how I populate the values:

class BoringForm(Form):
    until = DateTimeField("Until",
                          format="%Y-%m-%dT%H:%M:%S", 
                          default=datetime.today(),
                          validators=[validators.DataRequired()])

However, this is generated only once, server-side, which means that tomorrow I'll still get yesterday's date. I tried passing obj=something to the constructor, where something was an OrderedDict with a key called since, but it didn't work. Ideas?

Paleface answered 11/12, 2014 at 10:55 Comment(0)
P
27

Just drop the brackets on the callable:

class BoringForm(Form):
    until = DateTimeField(
        "Until", format="%Y-%m-%dT%H:%M:%S",
        default=datetime.today, ## Now it will call it everytime.
        validators=[validators.DataRequired()]
    )
Panel answered 11/12, 2014 at 14:5 Comment(1)
I see, "may be a callable" actually means something :) thanks!Paleface
F
0

I stumbled upon this, and the answer from @Doobeh is not enough for me, as I want two dates - today and "in two weeks day".

So here's general code using constructor.

def __init__(self, formdata=None, obj=None, **kwargs):
   super().__init__(formdata=formdata, obj=obj, **kwargs)

   self.date_from.data = datetime.today()
   self.date_to.data = datetime.today() + timedelta(days=14)
Financier answered 4/2, 2022 at 18:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.