Creating User-Friendly URLs in Django
In Django, a URL is the address of a specific web page or resource on your website. It is the part of the web address that comes after the domain name, and specifies the location of a resource on the server.
A URL pattern is a string that defines the structure of a URL. It is used to match URLs to specific views in your Django application.
The URL definitions and the view functions that they call in a Django Web application are loosely coupled, which means that the choice of the URL for a specific function and the implementation of the function itself are made in two different locations.
Views in Django are Python methods that take a URL request as a parameter and either return an HTTP response or throw an error, such as a 404, depending on the situation. Each view needs to be associated with a certain URL pattern. This is accomplished using the URLConf Python package (URL configuration)
A URLconf (URL configuration) is a set of URL patterns that Django uses to determine which view to display for a given URL. It is a Python module that contains a list of patterns that Django should match against incoming URLs, and the view function that should be called for each matched URL.
Here is an example of a simple URLconf in Django:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
In this example, the urlpatterns list contains four path patterns that match different URLs. The first pattern matches the root URL (/) and calls the index view function. The other three patterns match URLs with a question_id parameter and call different view functions based on the URL.
To use a URLconf in your Django application, you need to include it in your project’s ROOT_URLCONF setting.
For example:
ROOT_URLCONF = ‘myproject.urls’