[Python] Trying to build a Flask webpage which stores username dynamically

Discussão em 'Python' iniciado por Stack, Janeiro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to build a Flask website in Python. The idea is that initially, the user will go to a login page, type their name into the input bar, and then the Home page will pop up saying 'welcome <username> '. Here is my code:

    from flask import Flask, render_template, request, url_for, redirect
    app = Flask(__name__)


    @app.route('/home/<username>')
    def home_page(username):
    message = f"Welcome {username}"
    return message
    #return render_template('home.html')


    # home route that returns below text when root url is accessed
    @app.route('/', methods=['POST', 'GET'])
    def login_page():
    if request.method == 'POST':
    username = request.form['username']
    return redirect(url_for('home_page', name=username))
    return render_template('login.html')


    @app.route('/contact')
    def contact_page():
    return render_template('contact.html')


    if __name__ == '__main__':
    app.run(debug=True)


    Here is the html script. It's very simple:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Login</title>
    </head>
    <body>
    <form
    action='http://127.0.0.1:5000/'
    method='POST' >

    <h1> Welcome to my Art! </h1>
    <br>
    <h2> First you must login... </h2>
    <label> Please enter your name: </label>
    <div>
    <input type="text" name="username" />
    </div>

    <div>
    <br>
    <button type="submit" name='submit'> Submit </button>
    </div>

    </form>

    </body>
    </html>


    However, when I type my name into the webpage and press the Submit button, this error message comes up:

    error message

    Could someone please help me with this?

    Continue reading...

Compartilhe esta Página