Can not go to another page using url_for inside html tag in Flask

Question:

I can not go to about_me page from the index page.
Error :

The requested URL was not found on the server.

and got url like "http://127.0.0.1:5000/%7B%7B%20url_for('about')%20%7D%7D".

from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def index():
    return '''
    <!DOCTYPE html>
<html lang="en">
<head>
    <title>Title</title>
</head>
<body>
<p>welcome home</p>
<a href="{{ url_for('about_me') }}">about</a>
</body>
</html>
'''
@app.route('/about')
def about_me():
    return 'about me'

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

||

Answers:

The formatting you’re using to insert the url_for the about me page, namely:

<a href={{url_for('about_me')}}">about</a>

Will only work inside of a Jinja template. Those templates get processed by the template engine before the response is returned, and during that processing the notation with the two braces {{ something }} gets recognized and interpreted differently.

Here however, you are not using this notation in a Jinja template, you are using it it in a normal string, a string that does not get processed and thus does not have anything replaced.

The correct way to achieve what you want, in this case would be to parameterize the string and pass the link through formatting. E.g:

@app.route('/')
def index():
    return '''
    <!DOCTYPE html>
<html lang="en">
<head>
    <title>Title</title>
</head>
<body>
    <p>welcome home</p>
    <a href="{about_me}">about</a>
    </body>
</html>
'''.format(about_me=url_for('about_me'))

Hope this helps!

Answered By: Tom P.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.