Flask : href link to html not working

16,062

You should use from flask import render_template, url_for

and in the template:

<h1>
The template has been rendered!!!<br>
<a href="{{ url_for('route1') }}">Route No. 1</a>
</h1>

Just let Flask and Jinja2 make the URL's for you...

*It seems that you forgot the trailing slash at the link. Should be localhost:8080/route/ But its far better to use url_for as it avoids this type of problem

Share:
16,062

Related videos on Youtube

Ishaan Verma
Author by

Ishaan Verma

Updated on June 04, 2022

Comments

  • Ishaan Verma
    Ishaan Verma almost 2 years

    I have a basic Flask app with the following structure :

    from flask import Flask
    from flask import render_template
    app = Flask(__name__,template_folder='E:\Programming\Python Projects\Flask')
    
    @app.route('/')
    def index():
        return render_template('hello.html')
    @app.route('/route/')
    def route1():
        return render_template('route1.html')
    app.run(debug = True,port = 8080,host = '0.0.0.0')
    

    hello.html :

    <!DOCTYPE html>
    <html>
    <head>
        <title>Rendered!!</title>
    </head>
    <body>
    <h1>
        The template has been rendered!!!<br>
        <a href="localhost:8080/route">Route No. 1</a>
    </h1>
    </body>
    </html>
    

    route1.html :

    <!DOCTYPE html>
    <html>
    <head>
        <title>Route No. 1</title>
    </head>
    <body>
    <h2>
        This is the first route!!!<br>
        Hello World!!!
    </h2>
    <iframe src="https://www.youtube.com/embed/YQHsXMglC9A" width="853" height="480" frameborder="0" allowfullscreen></iframe>
    </body>
    </html>
    

    When I open localhost:8080 it works fine. But when I click on the link, it says :

    The address wasnโ€™t understood
    Firefox doesnโ€™t know how to open this address, because one of the following protocols (localhost) isnโ€™t associated with any program or is not allowed in this context.
    

    It works fine when I type the address localhost:8080/route manually in the address bar. Also, it works fine when opened in a new tab. I need help!!! Thank You !!!

    • abagshaw
      abagshaw over 6 years
      Can you try changing the link to just /route making it relative instead of absolute? Alternatively you can add http:// as a prefix making the link http://localhost:8080/route.