I want to have a dynamic default value for a form. This will be whatever was inputted last time it was used.
I saw this answer that says to modify the default value after creation and then use the process() method. This works in updating it (I see the default displayed on the web page), but I get an error when the form submits saying The CSRF token is missing. In chrome devtools I see that the form has a input_id= 'csrf_token'
and a value so not sure what is happening?
class weight(FlaskForm):
weight = StringField('Enter your weight', validators=[DataRequired()])
submit = SubmitField('Submit')
last_weight = get_last_weight() # query database function, returns float (e.g 85.4)
form = weight()
form.weight.default = last_weight
form.process()
A related question, is this the best way to set a dynamic default? I tried
StringField('Enter your weight', validators=[DataRequired()], default=get_last_weight())
as the docs say
default – The default value to assign to the field, if no form or object input is provided. May be a callable.
so I think the function is a callable (tell me if I'm wrong!) but I get an error saying that the function is being used outside of the application context, so I think the function is being called too early. It seems like this would be a common task so guessing I have missed something.
Thanks!
This is how I like to handle dynamic form building
def buildWeightForm(last_weight):
class weight(FlaskForm):
weight = StringField('Enter your weight', default=last_weight, validators=[DataRequired()])
submit = SubmitField('Submit')
return weight()
For your 2nd question, if you're getting an error doing this
StringField('Enter your weight', validators=[DataRequired()], default=get_last_weight())
Try the following (removing your parentheses from your function call):
StringField('Enter your weight', validators=[DataRequired()], default=get_last_weight)