使用Flask将表单数据发送到数据库

问题描述:

我创建了一个带有文本字段和按钮的简单网页。当我点击按钮时,我希望我的应用程序使用文本字段的内容更新数据库中的记录。似乎很简单,但我无法弄清楚我错过了什么。这里是我的代码迄今:使用Flask将表单数据发送到数据库

app.py样品

@app.route('/update-audit/', methods=['POST']) 
def update_audit(test_name, description): 
    cur = connect_db() 
    cur.execute('UPDATE audit SET description = ? WHERE test_name = ?', (description, test_name,)) 
    return render_template('clicked.html') 

audit.html样品

<form action="{{ url_for('update_audit') }}" method="post"> 
    <td>{{ row[2] }}</td> 
    <td> 
     <input type="text" id="desc" value="{{ row[3] }}" size="140"> 
     <input type="hidden" name="update_audit" value="{{ row[2] }}, desc"/> 
     <input type="submit" class="btn btn-success" value="Update"/> 
    </td> 
</form> 

clicked.html

<!DOCTYPE html> 
{% extends "layout.html" %} 
{% block content %} 
<body> 
{{ form.description }}<br /> 
</body> 
{% endblock %} 

表样品

id | tool name | test name | description 
======================================== 
1 | "tool1" | "test1" | "update me!" 

不知道如果我失去了一个重要的概念(我flask_wtf发挥各地,并没有得到任何地方),或者如果我是一个或两个步骤就可以实现这一点了。

为文本输入设置名称属性,以便与提交的表单一起发送。

<input name="description" type="text" id="desc" value="{{ row[3] }}" size="140"> 

更新您的视图函数以获取来自request的POST字典属性的描述。 test_name也需要更新为适当的值。

@app.route('/update-audit/', methods=['POST']) 
def update_audit(): 
    description = request.form.get('description') 
    test_name = request.form.get('update_audit') 
    cur = connect_db() 
    with cur: 
     cur.execute(
      'UPDATE audit SET description = ? ' 
      'WHERE test_name = ?;', (description, test_name,)) 

    # commit changes to the database 
    return render_template('clicked.html') 
+0

感谢您的回答,虽然我得到这个回溯:AttributeError:'请求'对象没有属性'POST' – Drew

+0

此外,我需要得到测试名称传递到update_audit,以便数据库知道哪一行我想更新。这应该发生在audit.html中,并且行[2]包含测试名称。 – Drew

+0

它应该是'request.form'而不是'request.POST' –

你render_template应该得到一个形式参数:

回报render_template(“clicked.html”,形式=形式)

这也是您所提供的代码中的表单是不明确在python中进行处理以及变量行来自哪里。

+0

行是来自数据库的iter数据的当前索引。当我加载审计。html,我传递一个查询的结果,要求表中的所有数据。 – Drew

想通了:

app.py样品

@app.route('/update-audit/', methods=['POST']) 
def update_audit(): 
    description = request.form.get('description') 
    test_name = request.form.get('test_name') 

    sql = 'UPDATE audit SET description=? WHERE test_name=?' 
    conn = sqlite3.connect(DATABASE) 
    cur = conn.cursor() 
    cur.execute(sql, (description, test_name)) 
    conn.commit() 
    conn.close() 

    return render_template('clicked.html', data=(test_name, description)) 

audit.html样品

<form action="{{ url_for('update_audit') }}" method="POST"> 
    <td> 
     <input type="hidden" name="test_name" value="{{ row[2] }}">{{ row[2] }}</input> 
    </td> 
    <td> 
     <input type="text" name="description" id="desc" value="{{ row[3] }}" size="100" maxlength="140"/> 
     <input type="submit" class="btn btn-success" value="Update"/> 
    </td> 
</form> 
</tr> 

答案是正确的SQL-炼金命令的组合,并确保我通过audit.html中的两个输入标签将数据发送到update_audit函数。