Home > Software engineering >  BadRequestKeyError werkzeug.exceptions.BadRequestKeyError: KeyError: 'nume_pacient'
BadRequestKeyError werkzeug.exceptions.BadRequestKeyError: KeyError: 'nume_pacient'

Time:11-30

I want to get the text from my input with name="nume_pacient" when pressing the button, to pass it to python code and use it in a query in a database; I want the results to be loaded in the same page.

HTML PAGE:

{% extends "base.html" %}
{% block title %}Home{% endblock %}

{%block content %}
    <h1>This is the home page</h1>  
    <br>
    <button><a href="/populare/">Populare</a></button>     
    <button><a href="/pacienti/">Afisare Pacienti</a></button>
    <button><a href="/retete/">Afisare Retete</a></button>  
    <button><a href="/internari/">Afisare Internari</a></button>  
    <button><a href="/medici/">Afisare Medici</a></button>  
    <button><a href="/departamente/">Afisare Departamente</a></button>      
    {% for row in rows %}
        <p>
        {% for x in row %}
            {{x}}
        {% endfor %}
        </p>
    {% endfor %}
    <form method="POST">
        <input type="text" name="nume_pacient">
        <button><a href="/pacienti/cautare">Cautare Pacient</a> </button>
    </form>     
{%endblock%}

PYTHON CODE:

@auth.route('/pacienti/cautare',methods=["GET","POST"])
def cautarePacient():
    if request.method == 'GET':
        numeCautare=request.form['nume_pacient']
        print(numeCautare)
        connection=sqlite3.connect('database.db')
        cursor=connection.cursor()
        cursor.execute("SELECT * FROM pacient WHERE nume='{{x}}'".format(x=numeCautare))
        rows=cursor.fetchall()
        for row in rows:
            print(row)
        connection.commit()
        return render_template("home.html",user=current_user,rows=rows)
    return '',204

I tried using request.method == 'POST' I tried using request.form.get('nume_pacient')

CodePudding user response:

Don't add a tags inside buttons (not only in form but everywhere), provide action attribute to form:

<form method="POST" action="/pacienti/cautare">
    <input type="text" name="nume_pacient">
    <button type="submit">Cautare Pacient</button>
</form>     

Then in your python code you need to get data sent by POST request, so:

@auth.route('/pacienti/cautare',methods=["GET","POST"])
def cautarePacient():
    if request.method == 'POST':
        numeCautare=request.form['nume_pacient']
        print(numeCautare)
        connection=sqlite3.connect('database.db')
        cursor=connection.cursor()
        cursor.execute("SELECT * FROM pacient WHERE nume='{{x}}'".format(x=numeCautare))
        rows=cursor.fetchall()
        # you don't need to commit after SELECT
        return render_template("home.html",user=current_user,rows=rows)
    return '',204
  • Related