How do I create a link to another html page?

url_for generates urls to routes defined in your application. There are no (or should probably not be any) raw html files being served, especially out of the templates folder. Each template should be something rendered by Jinja. Each location you want to display or post a form to should be handled and generated by a route on your application.

In this case, you probably want to have one route to both render the form on GET and handle the form submit on POST.

__init__.py:

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

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/cool_form', methods=['GET', 'POST'])
def cool_form():
    if request.method == 'POST':
        # do stuff when the form is submitted

        # redirect to end the POST handling
        # the redirect can be to the same route or somewhere else
        return redirect(url_for('index'))

    # show the form, it wasn't submitted
    return render_template('cool_form.html')

templates/index.html:

<!doctype html>
<html>
<body>
    <p><a href="{{ url_for('cool_form') }}">Check out this cool form!</a></p>
</body>
</html>

templates/cool_form.html:

<!doctype html>
<html>
<body>
    <form method="post">
        <button type="submit">Do it!</button>
    </form>
</html>

I don't know what your forms and routes actually do, so this is just an example.


If you need to link static files, put them in the static folder, then use:

url_for('static', filename='a_picture.png')

So what I just found was that if I don't wrap the href in parenthesis it works and I also created a link to return back a page

@app.route('/blog')
def blog():
    return '<h1>These are my thoughts on <a href=blog/2020/dogs>dogs</a></h1>'

@app.route('/blog/2020/dogs')
def blog2():
    return '<h3>these are my dogs <a href=../../blog>home</a></h3>'

Tags:

Python

Flask