Reputation: 323
Good evening to everyone who reads this post. I want to add a select box to my web site in flask, but i can not understand how to set up html for that I look forward to see any comments and suggestions :)
My python code:
class selectmenu(Form):
month = SelectField('Choose month',choices=[('dec', 'dec'), ('yan', 'yan'), ('feb', 'febt')])
@app.route('/searchemp/', methods=['GET', 'POST'])
def searchemp():
form = selectmenu(request.form)
m = form.month.data
HTML:
<form action="" class="form-signin" method="post">
<h2 class="form-signin-heading" align="center">title</h2>
<input type="text" class="form-control"
placeholder= "username" name="username" value="{{request.form.username}}" required autofocus>
<!--
<input type="text" class="form-control"
placeholder= "month" name="month" value="{{request.form.month}}">
-->
<select name="month">
<option value="{{request.form.month}}">dec</option>
<option value="{{request.form.month}}">yanuary</option>
<option value="{{request.form.month}}">feb</option>
<option value="{{request.form.month}}">mar</option>
</select>
<button class="btn btn-lg btn-success btn-block" type="submit">Search</button>
<br>
<p align="center">{{error}} </p>
</form>
Upvotes: 2
Views: 3123
Reputation: 4302
Jinja2 template engine will render selectfield with choices, you dont have to create a html select field, jinja2 already does. And if you need to check form submission use validate_on_submit()
or request.method == 'POST'
:
class SelectMenu(Form):
month = SelectField('Select Month', choices=[(1, 'January'), (2,'February')])
@app.route('/searchemp/', methods=['GET', 'POST'])
def searchemp():
form = SelectMenu(request.form)
if form.validate_on_submit():
# get posted data
m = form.month.data
return render_template('index.html', form=form)
# index.html
<form action="" method="POST">
{{form.month.label}}{{form.month}}
</form>
Upvotes: 1