I have a form with two simple inputs (simplified for this question): first is a dropdown menu to select colors and the other one is input field for integer value. This form is multiplied dynamically in one page (there is a button on the page that is used to add another form) with form prefixes having all forms independent.
Here is the code for the form:
class EnvelopeForm(FlaskForm):
line_color = SelectField('Line color', choices=['blue', 'black', 'green'], validators=[DataRequired()])
line_width = IntegerField('Line width', default=2, validators=[DataRequired()])
submit = SubmitField('calculate')
After submitting, this data is written in DB like this:
class Envelope(db.Model):
id = db.Column(db.Integer, primary_key=True)
line_color = db.Column(db.String(20))
line_width = db.Column(db.Integer, default=2)
def __repr__(self):
return f"Envelope('{self.id}', '{self.line_color}', '{self.line_width}')"
In views.py I have an extra function that gathers the data from DB from a particular form inputs. I use this function to return the values from DB back in the fields of the particular forms in jinja.
This is the function:
def default_value(form_id):
return Envelope.query.filter_by(id=form_id).first()
And this is how I return the values from DB using that function:
{{ envelope_form.line_color.label }}
{{ envelope_form.line_color(class="", value=default_value(envelope_form.id).line_color) }}
{{ envelope_form.line_width.label }}
{{ envelope_form.line_width(class="", selected=default_value(envelope_form.id).line_width) }}
This works only for IntegerField but not for SelectField. If I change the number for line_width it stays the same regardless of page refresh or adding another form to the page. When I change the color from dropdown menu for one form it changes in DB but not return in the form field after I add another form to the page. Though in the source info it seems to be correct selected value. Regardless of my color choice it is always back to 'blue' after I add another form:
So my question is why it is working for IntegerField but doesn't work for SelectField?