Skip to content

django


Django path function

Signature

path(route, view, kwargs=None, name=None)

route

  • route is a string that contains a URL pattern.
  • patterns can contain variables.
  • when processing a request, Django starts at the first pattern in urlpatterns and makes its way down the list until it finds one that matches.
  • variables are written in <> angle brackets and have a type and name.
  • variables can be typed as str, int and slug (this-is-a-slug) ```python #

## view
- When Django finds a matching pattern, it calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments. 

## kwargs
Arbitrary keyword arguments can be passed in a dictionary to the target view. We aren’t going to use this feature of Django in the tutorial.

## name
Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.

## Example

```python
urlpatterns = [
    path('articles/2003/', views.special_case_2003), #path 1
    path('articles/<int:year>/', views.year_archive), #path 2
    path('articles/<int:year>/<int:month>/', views.month_archive), #path 3
    path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail), #path 4
]
# URL example View Function Call
1 mydomain.com/articles/2003/ views.special_case_2003(http_request_object)
2 mydomain.com/articles/2019/ views.year_archive(http_request_object, year=2019)
3 mydomain.com/articles/2020/05 views.month_archive(http_request_object, year=2020, month=5)
4 mydomain.com/articles/2022/06/we-shall-fall/ views.article_detail(http_request_object, year=2022, month=6, slug=we-shall-fall)

See also