Home > database >  if request.method == 'POST' and 'sub' in request.form: is not working in flask:
if request.method == 'POST' and 'sub' in request.form: is not working in flask:

Time:11-06

I'm doing a CRUD operation using flask and sqlalchemy. there're two input fields.

  1. Subject and 2) Description and an ADD button. User enters the values and Add it to the database (sqlite3). Fortunately that's working. Even deletion is working.

But updating a row is not working.

I'm attaching my Flask code.

@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 %}

CodePudding user response:

I don't have Flask setup, but I think your problem is here:

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

This statement is saying "if request.method is POST, and 'subb' is true, and 'dess' is an element of request.form (which is a dictionary I believe -- so this last part is what is always returning false.)

request.form is a dictionary, and you want to check that both 'subb' and 'dess' are keys in that dictionary right?

This should work:

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

CodePudding user response:

I modified the code like this, and working fine.

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

Thankyou @MattBlaha for the help.

  • Related