Flask - 存储模板的下拉值

时间:2014-05-25 18:03:44

标签: python flask

我正在使用Flask / Postgres应用程序并遇到我已经构建的下拉列表的问题 - 我无法弄清楚如何从我的数据库中的下拉列表中存储选定的值。请让我知道我错过了什么。我已经google了,但大多数相关的答案都与PHP而不是Flask有关。

这是我的烧瓶视图:

@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="")

这是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>

1 个答案:

答案 0 :(得分:3)

您需要纠正一些事项。

首先,Flask视图应同时具有GET和POST,我会将您的视图代码重新排列为:

@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)

您只需要在代码中使用一次render_template。它的工作方式是当GET请求被触发时,即您第一次访问url / logworkout时,将显示一次输入和发布的表单,然后将重定向到主页或任何地方。

在表单代码中,表单操作不应为空。您需要使用url_for()方法

来调用视图

更改此

# Incorrect
<form action="" method='post'>

# Correct
<form action="{{ url_for('post_log_workout') }}" method='post'>