Artem Kuznetsov
Artem Kuznetsov

Reputation: 19

redirecting to diffrent routes in flask

I have this route in flask :

@app.route("/welcome/<string:book_isbn>",methods=["GET", "POST"])
def book(book_isbn):

and i have an html file , which has the following link :

<a href="{{ url_for('welcome',book_isbn=book.isbn)}}">

where book.isbn is a variable that i passed earlier when rendering this html file .

when clicking on the link iam hoping to achieve that it will go to the route i mentioned

but instead it goes to this route :

@app.route("/welcome",methods=['GET','POST'])
def welcome():

and in the web browser on top i can see the route welcome?book_isbn=xxxxxx (x is just some number)

so i think the '?' is the problem, but i cant wrap my head around on whats causing it .

Upvotes: 0

Views: 44

Answers (1)

Cblopez
Cblopez

Reputation: 586

You might've checked but... Did you confirm that book.isbn is a string?

The ? appears when the url_for function has parameters that do not match with the existing routes, so there is a problem with that <string:book_isbn>. Docs here

You can try with one of the following lines:

type(book.isbn) # Should return "str"
isinstance(book.isbn, str) # Should return True

Edit

Try to route both routes into a single one with an optional parameter:

@app.route("/welcome",methods=['GET','POST'])
@app.route("/welcome/<string:book_isbn>",methods=['GET','POST'])
def book(book_isbn=None):
    if book_isbn:
        pass
    else:
        pass

Upvotes: 1

Related Questions