2017-10-11 88 views
-1

我創建了一個帶有文本字段和按鈕的簡單網頁。當我點擊按鈕時,我希望我的應用程序使用文本字段的內容更新數據庫中的記錄。似乎很簡單,但我無法弄清楚我錯過了什麼。這裏是我的代碼迄今:使用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發揮各地,並沒有得到任何地方),或者如果我是一個或兩個步驟就可以實現這一點了。

回答

1

爲文本輸入設置名稱屬性,以便與提交的表單一起發送。

<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' –

0

你render_template應該得到一個形式參數:

回報render_template(「clicked.html」,形式=形式)

這也是您所提供的代碼中的表單是不明確在python中進行處理以及變量行來自哪裏。

+0

行是來自數據庫的iter數據的當前索引。當我加載審計。html,我傳遞一個查詢的結果,要求表中的所有數據。 – Drew

0

想通了:

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函數。

相關問題