[FIXED] Could not build url for endpoint 'user_page'. Did you forget to specify values ['name']?

Issue

I have small code written in Flask and When I try to run my server and enter login and password, it gives me error named: werkzeug.routing.BuildError: Could not build url for endpoint ‘user_page’. Did you forget to specify values [‘name’]?

How can I fix that?

flask:

from flask import Flask, url_for, request, redirect, render_template

app = Flask(__name__)

@app.route('/page/<name>')
def user_page(name):
    return f"Welcome {name}"

@app.route('/error')
def error():
    return f"Sorry, you enter wrong username/password"

@app.route('/login', methods=['POST', 'GET'])
def login_page():
    password = request.form['usrp']
    username = request.form['usrn']

    if password == '123' and username == 'anon':
        if request.method == ['POST']:
            return redirect(url_for('user_page', name=username))

        else:
            username = request.args.get('usrn')
            return redirect(url_for('user_page', name=username))

    else:
        return redirect(url_for('error'))

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

HTML:

<html>
    <head>
        <title>TEST SITE</title>
    </head>

    <body>
        <div>
            <form action="http://localhost:5000/login" method="post">
                <p>Enter your name: <input type="text" name="usrn"></p>
                <p>Enter your password: <input type="password" name="usrp"></p>
                <p><input type="submit" value="submit"></p>
            </form>
        </div>
    </body>
</html>

Solution

The problem is not the redirect or url_for function, the problem is the value you pass into the argument ‘name’. If you print the username right before trying to use the url_for function, you will see that the value for username is ‘None’.

So to solve your problem, make sure that the value for ‘username’ is not ‘None’ when passing it into the url_for function!

Answered By – GerritKruse

Answer Checked By – Timothy Miller (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published