if request.method == 'POST' and 'sub' in request.form: is not working in flask: if condition is not executing

if request.method == 'POST' and 'sub' in request.form: is not working in flask: if condition is not executing

我正在使用 flask 和 sqlalchemy 进行 CRUD 操作。有两个输入字段。

  1. 主题和 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 %}

我没有安装 Flask,但我认为你的问题出在这里:

if request.method == 'POST' and 'subb' and 'dess' in request.form:

这个语句是说“如果 request.method 是 POST,并且 'subb' 是真的,并且 'dess' 是 request.form 的一个元素(这是我相信一本字典——所以这最后一部分总是返回错误。)

request.form 是一个字典,您想检查 'subb' 和 'dess' 都是该字典中的键吗?

这应该有效:

if request.method == 'POST' and all(elem in request.form.keys() for elem in ['subb','dess'):

我这样修改了代码,并且工作正常。

@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 的帮助。