我正在使用 Flask 和 sqlalchemy 進行 CRUD 操作。有兩個輸入欄位。
- 主題和 2) 描述和一個添加按鈕。用戶輸入值并將其添加到資料庫 (sqlite3)。幸運的是,這是有效的。甚至洗掉作業。
但是更新一行不起作用。
我附上了我的Flask代碼。
@app.route('/update/<id>/', methods = ['GET','POST'])
def update(id):
subj = ''
descr = ''
print("outside the if condition")
if request.method == 'POST' and 'subb' and 'dess' in request.form:
print("inside the if condition")
subj = request.form.get('sub')
print(subj)
descr = request.form.get('desc')
entry = Crud(subject = subj, description = descr)
db.session.add(entry)
db.session.commit()
searchThisId = Crud.query.get(id)
return render_template("update.html",searchThisId = searchThisId)
HTML
{% extends 'base.html' %}
{% block title %} Update the details {% endblock %}
{% block contents %}
<div>
<form method = 'POST', action = '/'>
<input type = "text" name = "subb" value = {{ searchThisId.subject }}><br>
<input type = "text" name = "dess" value = {{ searchThisId.description }}><br>
<input type = "submit" value = "UPDATE">
</form>
</div>
{% endblock %}
uj5u.com熱心網友回復:
我沒有 Flask 設定,但我認為您的問題在這里:
if request.method == 'POST' and 'subb' and 'dess' in request.form:
這個陳述句是說“如果 request.method 是 POST,并且 'subb' 是真的,并且 'dess' 是 request.form 的一個元素(我相信這是一本字典——所以最后一部分總是回傳 false。 )
request.form 是一本字典,您想檢查 'subb' 和 'dess' 是否都是該字典中的鍵,對嗎?
這應該有效:
if request.method == 'POST' and all(elem in request.form.keys() for elem in ['subb','dess'):
uj5u.com熱心網友回復:
我像這樣修改了代碼,并且作業正常。
@app.route('/update/<id>/', methods = ['POST','GET'])
def update(id):
searchThisId = Crud.query.get(id)
if request.method == 'POST':
searchThisId.subject = request.form['subb']
searchThisId.description = request.form['dess']
db.session.commit()
return redirect(url_for('Index'))
else:
return render_template("update.html",searchThisId = searchThisId)
HTML
<form method = 'POST', action = "/update/{{ searchThisId.id }}/">
<input type = "text" name = "subb" value = {{ searchThisId.subject }}><br>
<input type = "text" name = "dess" value = {{ searchThisId.description }}><br>
<input type = "submit" value = "UPDATE">
</form>
謝謝@MattBlaha 的幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/350576.html
