In this Flask Tutorial we are going to talk about Creating Dynamic URL in Flask,
so in any application when you have more than one routes, you need to include the
route links for connecting of different pages, so the user can easily navigate to different
pages of your application, for example if you have a navigation bar in your web application
you can simply add your Dynamic URL’s in their. there are two ways that you can add this kind
of functionality in your Flask Application, the first way is that you can add directly your
URL link’s in your template. but it is not the recommended way, if you have simple routes
than you can add directly your URL link’s. but for dynamic and complex routes it is not
good idea. the second way is using the url_for() helper function, Flask provides the url_for()
helper function, which generates URLs from the information stored in the application’s
URL map.
If you are interested in Web Development with Django Framework, than you can read the
complete articles in this link, Django Web Development Tutorials.
Adding Directly URL Link’s
In this way you can simply add your URL Link’s, in this article we are using our previous
articles source code. we are going to add our URL Link’s in our base.html, because our
navbar is located in the base.html.
So first of all this is our app.py file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
from flask import Flask, render_template #create the object of Flask app = Flask(__name__) #creating our routes @app.route('/') def index(): return render_template('index.html') #contact routes @app.route('/contact') def Contact(): return render_template('contact.html') @app.errorhandler(404) def page_not_found(e): return render_template('404.html') @app.errorhandler(500) def internal_server_error(e): return render_template('500.html') #run flask app if __name__ == "__main__": app.run(debug=True) |
templates/base.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %} {% endblock %}</title> <!-- CSS Bootstrap CDN Link --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <a class="navbar-brand" href="/">CodeLoop</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="contact">Contact</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Logout</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </div> <a href=""><button class="btn btn-success navbar-btn">Login</button> </a> <a href=""><button class="btn btn-success navbar-btn">Signup</button> </a> </nav> <!-- JS, Popper.js, and jQuery --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> {% block body %} {% endblock %} </body> </html> |
So the above code is our base.html, and we have just added directly our contact and home link in our navigation like this .
1 2 3 |
<li class="nav-item"> <a class="nav-link" href="contact">Contact</a> </li> |
1 |
<a class="navbar-brand" href="/">CodeLoop</a> |
templates/index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
{% extends 'base.html' %} {% block title %} Home {% endblock %} {% block body %} <div class="container"> <h1>Home Page - Welcome to codeloop.org</h1> <h3>Tutorial Number 7 </h3> <p> In this tutorial we are going to talk about flask URL helper function. </p> </div> {% endblock %} |
templates/contact.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
{% extends 'base.html' %} {% block title %}Contact {% endblock %} {% block body %} <div class="container"> <h1>Contact Page - Welcome to codeloop.org</h1> <h3>Tutorial Number 7 </h3> <p> In this tutorial we are going to talk about flask URL helper function. </p> </div> {% endblock %} |
These are our Custom error pages in flask that we have already created, you can read this
article for Flask Custom Error Page.
templates/404.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
{% extends 'base.html' %} {% block title %}Page Not Found {% endblock %} {% block body %} <div class="container"> <h1>Page Not Found</h1> </div> {% endblock %} |
templates/500.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
{% extends 'base.html' %} {% block title %}Server Error {% endblock %} {% block body %} <div class="container"> <h1>Internal Server Error </h1> </div> {% endblock %} |
Now if you run your Flask Application, and after that click on the contact, you can see
that we are navigating to the contact page.
Adding URL Link’s with url_for()
So as i have said Flask provides url_for() helper function for adding dynamic routes and it is one of the recommended way of adding URL Link’s. this function takes the view function name (or endpoint name for routes defined with app.add_url_route()) as its single argument and returns its URL. you need to bring change in your base.html. you can use url_for helper function like this.
1 2 |
href = {{url_for('index')}} href = {{url_for('Contact')}} |
Make sure that you have the same view function name in here.
After change, this is our base.html.
templates/base.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %} {% endblock %}</title> <!-- CSS Bootstrap CDN Link --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <a class="navbar-brand" href="{{url_for('index')}}">CodeLoop</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{{url_for('index')}}">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="{{url_for('Contact')}}">Contact</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Logout</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </div> <a href=""><button class="btn btn-success navbar-btn">Login</button> </a> <a href=""><button class="btn btn-success navbar-btn">Signup</button> </a> </nav> <!-- JS, Popper.js, and jQuery --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> {% block body %} {% endblock %} </body> </html> |
If you run the code the result will be the same, but this time we have used url_for()
helper function. also you can use url_for() for dynamic routes, for example you can pass
the name of your URL function.
You can use the view function like this.
1 2 3 |
@app.route('/answer/<int:answer_id>') def my_answer(answer_id): return ('My answer is {0}'.format(answer_id)) |
And in the url_for() you can do like this.
1 |
<a href = "{{ url_for('my_answer' ,answer_id=1) }}">Answer 1</a> |
Also you can watch my complete 4 hours training on Flask Web Development
Subscribe and Get Free Video Courses & Articles in your Email