I'm very new to using Flask and I'm trying to make a simple script to visualize the data I have stored in my database (basically a bunch of products, categories and some other things, all from vending machines), I did the main menu page and the 'categorias' (category) page, where I'm able to see all the categories (of products) in my system, and since categories can have sub-categories I made another page where I can see all the 'sub_categorias' (sub-categories) of the category I want.
For this I made a link from my 'categorias.html' file to 'categorias/sub_categorias?nome={{ record[0] }}', ('nome' being name in my language, and being the name of the "super category" of this sub-category), like so:
<a href="categorias/sub_categorias?nome={{ record[0] }}"> Sub categorias </a>
and it works fine, linking to a new page where the form "nome" is correct, like so:
but as you can see I get a Bad request error, that I think happens because in my python code, when I do request.form["nome"]
it for some reason doesn't get anything, when it should get Sopa
. Here's my code:
# Show all the sub-categories of a catgory.
@app.route("/categorias/sub_categorias")
def show_sub_categories():
dbConn = None
cursor = None
try:
dbConn = psycopg2.connect(DB_CONNECTION_STRING)
cursor = dbConn.cursor(cursor_factory = psycopg2.extras.DictCursor)
# Gets all the sub-categories of the super category given.
query = "SELECT categoria FROM tem_outra WHERE super_categoria=%s;"
# Gets the data we need from the URL query string.
data = (request.form["nome"])
cursor.execute(query, data)
return render_template("sub_categorias.html", cursor = cursor, params = request.args)
except Exception as e:
return str(e)
finally:
cursor.close()
dbConn.close()
For extra context here's my 'categorias.html' file body (although I'm almost certain the problem comes from here):
<h1> Categorias </h1>
<div id="table">
<button onclick="window.location.href='menu'"> Menu principal </button>
<button onclick="window.location.href='categorias/inserir_categoria'"> Inserir categoria </button>
<button onclick="window.location.href='categorias/remover_categoria'"> Remover categoria </button>
<table id="Category_table">
<thead>
<tr>
<th> Nome </th>
<th> Gerir </th>
</tr>
</thead>
<!-- For loop to fetch all the system's categories. -->
{% for record in cursor %}
<tr>
<td> {{ record[0] }} </td>
<td>
<a href="categorias/sub_categorias?nome={{ record[0] }}"> Sub categorias </a>
</td>
</tr>
{% endfor %}
</table>
</div>
I really don't know what I'm doing wrong, so if someone could help me I'd very much appreciate it, Thanks.