Django URLs in 100 words
Series: X in 100 words
The next component of Django to cover is another key component of building a website, URLs or more precisely URL patterns. There are two types of URLs in Django, static and dynamic.
Static urls are fixed (eg /about
or /team
). these are the simplest urls to implement as follows:
path('about', views.about, name='about'),
path('team', views.team, name='team'),
Dynamic urls can capture certain aspects of a URL as a variable to pass to the view. For example looking at a profile page or an item in an online store. Variable capture includes strings, integers, slugs, uuid, paths or a custom regex. This is used as follows:
path("articles/<int:year>/", views.year_archive),
path("articles/<int:year>/<int:month>/", views.month_archive),
Here we have 2 urls, the first has a single argument named year
that is passed as an integer to the view and the second view passed year
and month
to a view as integers.
Finally Django URLs have the include
function, this allows the nesting of urlpatterns under a common prefix. This is useful for simple organisation or the reuse of a set of URLs in multiple contexts (eg reusable apps), for example:
# in articles/urls.py
url_patterns = [
path("<int:year>/", views.year_archive),
path("<int:year>/<int:month>/", views.month_archive),
]
# in project/urls.py
path('articles/', include('articles.urls'))