Search code examples
pythonhtmlflaskbutton

Flask - Make a button direct to another page


On my main page I have a button that says "Enter"

<button id="Enter" type="button" onclick="/profile" class="button">Enter</button>
</div>

I would like it so that when this button is clicked it directs to the "home" page

Python code:

@app.route('/', methods = ['GET', 'POST'])
def index():
    return render_template("main.html")

@app.route('/home', methods = ['GET', 'POST'])
def home():
    return render_template("test1.html")

How can this be done? Thanks


Solution

  • This is the job of an anchor tag.

    Jinja2 (the template rendering component of Flask) allows you to use the url_for function to dynamically create a url, for a given view function.

    In your case:

    <a href="{{ url_for('home') }}">Home</a>
    

    With your code, this will render in the browser as:

    <a href="/home">Home</a>
    

    Even if you change the endpoint in the app.route decorator function this will render with the correct URL.

    To give this the appearance of a button, I would suggest using the Bootstrap library. This can be included from a CDN by adding the following within the head of your HTML template:

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.0/css/bootstrap.min.css" integrity="sha256-/ykJw/wDxMa0AQhHDYfuMEwVb4JHMx9h4jD4XvHqVzU=" crossorigin="anonymous" />
    

    Then assigning the button styling is as simple as adding a class attribute to your anchor tag:

    class='btn btn-primary'
    

    See the other available classes in the bootstrap docs