We use url_for to create web addresses inside our Flask app easily. It helps keep links correct even if we change routes later.
0
0
URL building with url_for in Flask
Introduction
When you want to link to another page in your Flask app without typing the full URL.
When you want to avoid hardcoding URLs so your app stays easy to update.
When you need to generate URLs with dynamic parts like user IDs or post names.
When you want to keep your code clean and avoid mistakes in URLs.
When you want to use URLs in templates or redirects safely.
Syntax
Flask
url_for(endpoint, **values)
endpoint is the name of the function that handles the route.
values are optional keyword arguments for dynamic parts of the URL.
Examples
Builds the URL for the function named
index. Usually the home page.Flask
url_for('index')Builds a URL for the
profile function with a dynamic username part set to 'alice'.Flask
url_for('profile', username='alice')
Builds the URL for a static file like CSS or images.
Flask
url_for('static', filename='style.css')
Sample Program
This example shows how to use url_for to build URLs for the home page, a user profile page with a username, and a static file. The test_request_context lets us call url_for outside a real web request for testing.
Flask
from flask import Flask, url_for app = Flask(__name__) @app.route('/') def index(): return 'Home Page' @app.route('/user/<username>') def profile(username): return f"User: {username}" with app.test_request_context(): print(url_for('index')) print(url_for('profile', username='bob')) print(url_for('static', filename='logo.png'))
OutputSuccess
Important Notes
Always use url_for instead of hardcoding URLs to keep your app flexible.
If your route has dynamic parts, you must provide matching arguments to url_for.
You can use url_for in templates by importing it or using Flask's built-in support.
Summary
url_for helps build URLs by using route function names.
It keeps links correct even if routes change.
Use it with dynamic parts by passing keyword arguments.