Django URL Templates | python

Python Methods and Functions

In Django, views — these are Python functions that take a URL request as a parameter and return an HTTP response or throw an exception like 404. Each view must be matched against a matching URL pattern. This is done using the Python URLConf (URL setting) module

Let the project name be myProject. The Python module to be used as URLConf is the ROOT_URLCONF value in myProject/ . By default this is set to & # 39; myProject.urls & # 39; . Each URLConf module must contain a urlpatterns variable that is a set of URL patterns to match against the requested URL. These patterns will be checked sequentially until the first match is found. Then the view corresponding to the first match is called. If the URL pattern does not match, Django invokes the appropriate error handling view.

Including other URLConf modules
It is good practice to have an URLConf module for every application in Django. This module must be included in the root URLConf module as follows:

from django.contrib import admin

from django.urls import path, include


urlpatterns = [

path ( 'admin /' ,,

path (' ', include (' books.urls')),


This tells Django to look for URL patterns in the file books / urls. py

URL Patterns

Here's some sample code for books /

from django.urls import path

from import views


urlpatterns = [

path ( 'books / & lt; int: pk & gt; /' , views.book_detail),

path ( 'books / & lt; str: genre & gt; /' , views.books_by_genre),

path ( 'books /' , views.book_index), 


For example,

  • A URL request to / books / crime / will match the second URL pattern. As a result, Django will call the views.books_by_genre (request, genre = crime) function.
  • Similarly, a request for the URL / books / 25 / will match the first URL pattern, and Django will call the views.book_detail (request, pk = 25) .

Here int and str are path converters and captures an integer and a string, respectively.

Path converters:
The following types of path converters are available in Django

  • int — Matches zero or any positive integer.
  • str — matches any nonblank string except the path separator (& # 39; / & # 39;).
  • slug — matches any slug string, that is, a string consisting of alphabets, numbers, hyphens, and underscore.
  • path — matches any nonblank string, including the path separator (& # 39; / & # 39;)
  • uuid — matches the UUID (universally unique identifier).