I have a form which has a drop down and other field value. The choice which has been selected by user is not getting selected and getting an error, not a valid choice. I don't know where the exact problem is, but the form on submit is checking whether all fields are filled or not and then raise error for the first field not a valid choice.
Here is my HTML code:
<select name="Product">
{% for choice in choices %}
<option value="{{ choice }}" > {{ choice }} </option>
{% endfor %}
</select>
Form:
class myForm(FlaskForm):
product = SelectField('Product', validators = [DataRequired()])
rate = FloatField('rate')
index = FloatField('index')
wind = FloatField('wind')
submit = SubmitField("Submit")
any help will be appreciated.
I don't know how you render your form, but the way you use the selectfield is the main cause of the problem you faced.
Here is step by step how to structure the code:
FLASK:
class myForm(FlaskForm):
product = SelectField('Product',validators=[DataRequired()])
rate = FloatField('rate')
index = FloatField('index')
wind = FloatField('wind')
submit = SubmitField("Submit")
@app.route('/home', methods=['GET', 'POST'])
def home():
form = myForm()
# Populating the product select field with data in your DB
form.product.choices = [(p.id, p.name) for p in Product.query.order_by(Product.name.asc()).all()]
if form.validate_on_submit():
# Getting form's data
product = form.product.data
return render_template('index.html', form=form)
HTML:
<form action='' method="POST" novalidate>
{{ form.hidden_tag() }}
{{ form.product.label }}
{{ form.product }}
{% for error in form.product.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</form>
Note how the product field is rendered in HTML using Jinja. The good news is that the fields that are defined in your form class know how to render themselves as HTML matching their respectives types.