Working with URLs in Django is an essential part of web development with dynamic applications. In other words, routing in Django helps us connect different user requests to appropriate views. This work involves configuring the web addresses (URLs) that point to views or specific functions in the application, allowing us to perform it.
Additionally, we can use permanent URLs to send more information through these URLs. For example, suppose we have a news website and want to display articles on the site. In this case, we can define the specific URL for selecting a particular article based on its identifier.
In Django, you need to first define your URLs in the urls.py
file. This file contains a collection of URL patterns, each associated with a view. To use this capability correctly, we need to have a good understanding of the URL configuration and how to utilize variables associated with them.
Let’s take a simple example and examine how to configure URLs and link them to corresponding views in Django. Below is an example of a urls.py
file and a corresponding view
:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('articles/', views.articles_list, name='articles_list'),
path('articles/<int:article_id>/', views.article_detail, name='article_detail')
]
Explanation Line by Line
from django.urls import path
This line imports the
path
module from django.urls
, which is used to define the routing paths. from . import views
This line imports the
views
module, which contains all the views you want to connect via the URL. urlpatterns = []
This line defines a list of URL patterns that each correspond to a view in the application.
path('', views.index, name='index')
This line assigns the main URL path that leads to the
index
view. path('articles/', views.articles_list, name='articles_list')
This URL is defined for listing articles, linking to the
articles_list
view. path('articles/<int:article_id>/', views.article_detail, name='article_detail')
This line defines a URL with an integer parameter for viewing the details of a specific article, where the article identifier is retrieved through the URL.