I have a form that I want to automatically fill some of the fields with information received on a previous page, but it needs to be changeable if they want to adjust it. I am using a dynamically created list for my SelectField that works, but adding the StringField has been unsuccessful. See my code below:
forms.py
class get_vals(var):
...
typs = var.p_typs
p_name = var.p_name
return typs,p_name
class NewForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
typ1 = SelectField('Type', validators=[Optional()])
def __init__(self,var):
super(NewForm,self).__init__()
typs,p_name = get_vals(var)
self.typ1.choices = typs
self.name.default = p_name
Using:
self.name.default
leaves my name form blank. If I use:
self.name.data
it puts the correct information in the form, however you cannot change the values and must use whatever it places in, which is not an option.
...
<form action="" method="post">
{{ form.hidden_tag() }}
<p>
{{ form.name.label }}
{{ form.name(size=24) }}
{{ form.typ1.label }}
{{ form.typ1() }}
</p>
...
Is there a way to set the default value which a variable and have it changeable? Thanks
UPDATE If I set the field I am trying to update to None after running the Form that gets the name variable, I am able to change the variable without error. However, it won't overwrite the form.name.data value
form = NewForm(var)
var.name == None
if form.validate_on_submit():
var.name = form.name.data
This runs (displays correct variable in form and is adjustable) but doesn't overwrite the value when you submit the form, how can I overwrite the value?
You can set initial values for fields by passing a
MultiDict
* asFlaskForm
'sformdata
argument.This will set the value of the
name
input to 'Foo' when the form is rendered, overriding the default value for the field. However you don't want to override the values when the form is posted back to the server, so you need to check the request method in your handler:* A MultiDict is required because in an HTML form there may be multiple inputs with the same
name
attribute, and a MultiDict has methods that handle lists of values as well as single values like a normaldict
.