All I need to complete this website is for it to grab the n
and s
values from the input.
But when executing request.get.args
is returning None everytime
Here's the code:
my_website.py
:
import sqlite3
from flask import Flask,render_template, url_for, redirect, request
app = Flask(__name__)
conn = sqlite3.connect('shoes.db', check_same_thread=False)
c = conn.cursor()
@app.route("/", methods=["GET", "POST"])
def main():
if request.method == 'GET':
return render_template('main.html')
elif request.method == 'POST':
return redirect(url_for('search'))
@app.route("/search/", methods=["GET", "POST"])
def search():
if not request.args.get("n"):
raise RuntimeError("missing n")
if not request.args.get("s"):
raise RuntimeError("missing s")
name = request.args.get('n')
size = request.args.get('s')
c.execute("SELECT * FROM shoes WHERE name LIKE ? AND sizes LIKE ? ORDER BY price",
('%'+name+'%','%'+size+'%'))
p = c.fetchall()
url = [p[i][0] for i in range(len(p))]
names = [p[i][1] for i in range(len(p))]
prices = [p[i][2] for i in range(len(p))]
sizes = [p[i][3] for i in range(len(p))]
shoe_type = [p[i][4] for i in range(len(p))]
return render_template('search.html' , url=url, names=names, prices=prices,
sizes=sizes, shoe_type=shoe_type)
if __name__ == '__main__':
app.run(debug=True)
main.html
:
{% extends "layout.html" %}
{% block content %}
<form action = "{{ url_for('main') }}" class="form" method = "POST" >
<div>
<h1>Soccer Shoes Finder</h1>
<div class="line-separator"></div>
<div>
<div class="container-fluid">
<input name = "n" type="text" placeholder="Name"/>
<input name = "s" type="text" placeholder="Size"/>
<button class="glyphicon glyphicon-search" aria-hidden="true"></button>
</div>
</div>
</form>
{% endblock %}
This is the error that I'm getting:
RuntimeError: missing n
Any advice would be appreciated. Thanks.
request.args is a MultiDict with the parsed contents of the query string. From the documentation of get method: get(key, default=None, type=None) Return the default value if the requested data doesn't exist.
The args attribute is a dictionary containing arguments from the URL. The get() method is a built-in dictionary method that will “get” an item from a dictionary or return a default value ( None if key not found). In this case, it avoids a KeyError if “name” argument not found.
request.args
holds the values in the query string. Your form on the other hand is sending values in the POST body.
Use the request.form
mapping instead, or use request.values
, which combines request.form
and request.args
.
Alternatively, change your form method
to GET
to have the browser put the arguments in the query string instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With