Reputation: 271
I'm working on a Flask / Postgres app and running into an issue with a dropdown I've built - I can't figure out how to store a selected value from the dropdown in my database. Please let me know what I'm missing. I have googled around but most of the relevant answers pertain to PHP not Flask.
Here's my flask view:
@app.route('/logworkout', methods=['POST'])
def post_log_workout():
try:
studio = (request.form.get['studio'])
instructor = (request.form.get['instructor'])
workout = Workout(studio=studio, instructor=instructor)
db.session.add(workout)
db.session.commit()
except:
return render_template("submit_workout.html", studio="", instructor="",
error="Error, your log is incomplete! Please check and submit it again!")
return render_template("submit_workout.html", studio=studio, instructor=instructor, error="")
Here's the HTML:
<form action="" method='post'>
<h3>2. Which Studio?</h3>
<select name='studio'>
<option value='Name1'>LongerName1</option>
<option value='Name2'>LongerName2</option>
<option value='Name3'>LongerName3</option>
</select>
<h3>2. Which Instructor?</h3>
<select name='instructor'>
<option value='Name1'>LongerName1</option>
<option value='Name2'>LongerName2</option>
<option value='Name3'>LongerName3</option>
</select>
<input type='submit' value='submit'>
</form>
Upvotes: 3
Views: 7470
Reputation: 33309
You have a few things to correct.
First, a Flask view should have both GET and POST and I would re-arrange your view code as:
@app.route('/logworkout', methods=['GET','POST'])
def post_log_workout():
error=""
if request.method == 'POST':
studio = (request.form.get['studio'])
instructor = (request.form.get['instructor'])
if studio is not None and instructor is not None:
workout = Workout(studio=studio, instructor=instructor)
db.session.add(workout)
db.session.commit()
# you can redirect to home page on successful commit. or anywhere else
return redirect(url_for('index'))
else:
error="Error, your log is incomplete! Please check and submit it again!")
return render_template("submit_workout.html", error=error)
You only need to have the render_template once in your code. The way it will work is when a GET request is fired i.e. you visit the url /logworkout first time, the form will be displayed which once entered and posted, will then redirect to home page or wherever.
In your form code, your form action should not be blank. You need to call the view by using url_for() method
Change this
# Incorrect
<form action="" method='post'>
to
# Correct
<form action="{{ url_for('post_log_workout') }}" method='post'>
Upvotes: 4