url_for() (Flask)

url_for() builds a URL to a view by its function name instead of hard-coding the path. It is used in templates and views so links keep working even if you change the route's URL pattern.

Flask

Hard-coded URLs break when you reorganize routes. url_for('profile', name='sam') asks Flask to generate the current URL for the profile view, passing name as a route parameter — Flask figures out the actual path from the URL map.

It also handles a few things automatically: extra keyword arguments that are not route parameters are appended as a query string, and url_for('static', filename='x.css') generates the correct URL for files in your static/ folder.

Inside Blueprints, prefix the endpoint with the blueprint name, like url_for('admin.dashboard'). This is the single most common url_for gotcha for newcomers.

Syntax

url_for("endpoint", param=value)
url_for("static", filename="style.css")

Examples

Python — Returns '/user/sam?ref=home'

from flask import url_for

@app.route("/")
def index():
    return url_for("profile", name="sam", ref="home")

@app.route("/user/<name>")
def profile(name):
    return name

Learn it in a lesson

See also

Back to the Dictionary