Search code examples
pythonhtmlformsflask

How to get the request tag in flask to work


For the past hour I have been trying to make the request tag work in flask..

this is my code in server.py:

@app.route('/login', methods=['post'])
def receive_data():
    user = request.form['username']
    password = request.form['password']
    return f'<h1>name:{user} password:{password}</h1>'

and in index.html its:

    <form action="{{ url_for('receive_data'}}" method="POST">
        <label>Name</label>
        <input type="text" placeholder="name" name="username">
        <label>Password</label>
        <input type="text" placeholder="password" name="password">
        <button type="submit">Ok</button>
    </form>

I also tried the request.form.get('username') but it returns none


Solution

  • Make sure to import the request object:

    from flask import Flask, request
    

    Hehe's the server.py:

    from flask import Flask, request, render_template
    app = Flask(__name__)
    @app.route('/')
    def index():
        return render_template('index.html')
    @app.route('/login', methods=['POST'])
    def receive_data():
        user = request.form.get('username')
        password = request.form.get('password')
        print(user)
        print(password)
        if user and password:
            return f'<h1>Name: {user}, Password: {password}</h1>'
        else:
            return '<h1>Missing username or password</h1>', 400
    if __name__ == '__main__':
        app.run(debug=True)
    

    Here's the HTML:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Login Page</title>
    </head>
    <body>
        <form action="{{ url_for('receive_data') }}" method="POST">
            <label for="username">Name:</label>
            <input type="text" id="username" name="username" placeholder="Enter your name">
            <br>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" placeholder="Enter your password">
            <br>
            <button type="submit">Login</button>
        </form>
    </body>
    </html>
    

    Do not forget to install Flask 😇!

    pip install Flask
    

    Updated for debugging 🤓.