(Python) Flask - request.args.get returning NoneType

11,174

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.

Share:
11,174
tadm123
Author by

tadm123

Updated on June 11, 2022

Comments

  • tadm123
    tadm123 almost 2 years

    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.