Siddhant
Siddhant

Reputation: 1

Building dynamic url in flask [werkzeug.routing.BuildError]


app = Flask(__name__)
#A basic flask function
@app.route('/')
def welcome():
    return "2+2"
    
#Building URL Dynamically
@app.route('/marks/<int:num>')
def dynamic(num):
    if num>95:
        return "The Student has got {} and got A+ grade".format(num)
    elif num <95:
        return "Alas, Student had got {} marks and got A grade".format(num)

@app.route('/dyna_url/<int:num1>')
def dynamical(num1):
    if num1<40:
        return "Alas, Student had failed in exam, with score {}".format(num1)

    elif num1 >=40 and num1<=90:
        return "The Student has passed in exam, with score {}".format(num1)

    elif num1 >90:
        return redirect(url_for("marks",num= num1))


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

I am unable to redirect using "return redirect(url_for("marks",num= num1))" statemen to the above function.

getting error - "werkzeug.routing.BuildError: Could not build url for endpoint 'marks' with values ['num']. Did you mean 'static' instead?"

Upvotes: 0

Views: 192

Answers (1)

Vishnu Joshi
Vishnu Joshi

Reputation: 333

I noticed that you have not created any Flask route named "marks". When we use the url_for function , it creates a URL for the function given in quotes.

So if we use url_for("dynamic", num = 90) , it creates a link using the path given for the function named "dynamic" ((from the decorator @app.route("/marks/<int:num>")) i.e. /marks/90 .

When using url_for, we must specify the function whose path we are using , and not the path we want to redirect it to.

You can either use this

elif num1 > 90:
    return redirect(f"/marks/{num1}"))

or

elif num1 > 90:
    return redirect(url_for("dynamic" , num= num1))

Upvotes: 1

Related Questions