How to Use url_for in Flask: Syntax and Examples
In Flask, use
url_for to generate URLs for routes or static files dynamically by passing the endpoint name and optional parameters. This helps avoid hardcoding URLs and keeps your app flexible and maintainable.Syntax
The url_for function takes the endpoint name (usually the function name of a route) as the first argument. You can pass additional keyword arguments to fill in dynamic parts of the URL or query parameters.
- endpoint: The name of the view function or 'static' for static files.
- kwargs: Optional parameters for dynamic URL parts or query strings.
python
url_for(endpoint, **values)
Example
This example shows how to use url_for to generate URLs for a route with a dynamic parameter and for a static file.
python
from flask import Flask, url_for app = Flask(__name__) @app.route('/') def index(): # Generate URL for the 'profile' route with username 'alice' profile_url = url_for('profile', username='alice') # Generate URL for a static CSS file css_url = url_for('static', filename='style.css') return f"Profile URL: {profile_url}<br>CSS URL: {css_url}" @app.route('/user/<username>') def profile(username): return f"User profile page of {username}"
Output
Profile URL: /user/alice
CSS URL: /static/style.css
Common Pitfalls
Common mistakes when using url_for include:
- Using the wrong endpoint name (it must match the view function name exactly).
- Not providing required dynamic parameters for routes with variables.
- Trying to use
url_foroutside an application context withoutapp.app_context().
Always check your route function names and parameters carefully.
python
from flask import Flask, url_for app = Flask(__name__) @app.route('/item/<int:id>') def item(id): return f"Item {id}" with app.app_context(): # Wrong: missing required 'id' parameter # url_for('item') # This will raise a BuildError # Correct: provide the 'id' parameter print(url_for('item', id=42)) # Outputs: /item/42
Output
/item/42
Quick Reference
- url_for('endpoint'): Generate URL for a route.
- url_for('endpoint', param=value): Fill dynamic URL parts.
- url_for('static', filename='file'): URL for static files.
- Use inside request or app context.
Key Takeaways
Use url_for with the route's function name to generate URLs dynamically.
Always provide required parameters for routes with dynamic parts.
Use url_for('static', filename='path') to link static files like CSS or images.
Avoid hardcoding URLs to keep your Flask app flexible and maintainable.
Ensure you call url_for within an application or request context.