Open In App

Django URLs in Python

Last Updated : 17 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Django, views are Python functions that handle HTTP requests. These views process the request and return an HTTP response or an error (e.g., 404 if not found). Each view must be mapped to a specific URL pattern. This mapping is managed through URLConf (URL Configuration).

In this article, we'll explore how URL patterns are used in Django, how they are defined in urls.py, and how different URL patterns help in routing requests to appropriate views.

Understanding URLConf in Django

In Django, the URLConf refers to the process of mapping URLs to views. This mapping is defined in a Python module, usually called urls.py. The configuration module specified in the ROOT_URLCONF setting in settings.py determines which module is used for URL mapping.

For a project named myProject, the default ROOT_URLCONF is typically set to 'myProject.urls'. Every URLConf module contains a variable urlpatterns, which is a list or set of URL patterns that Django checks against the requested URL. The patterns are checked in sequence, and when a match is found, the corresponding view is invoked. If no match is found, Django triggers an appropriate error handling view.

Structure of URLConf in Django:

Python
# myProject/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('books.urls')),  # Including URL patterns from the books app
]

In the above example:

  • path('admin/', admin.site.urls) maps the URL /admin/ to Django's default admin interface.
  • path('', include('books.urls')) tells Django to look for additional URL patterns in the books.urls module, which is typically located in the books app.

URL Patterns in Django

URL patterns are defined inside the urlpatterns list. This list contains the routes Django uses to match incoming URLs to appropriate views.

Here is a sample urls.py for the books app:

Python
# books/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('books/<int:pk>/', views.book_detail),  # Detail view for a book, identified by primary key (pk)
    path('books/<str:genre>/', views.books_by_genre),  # View books by genre
    path('books/', views.book_index),  # List all books
]

Explanation:

  • path('books/<int:pk>/', views.book_detail): This pattern matches /books/25/, where 25 is an integer representing the primary key (PK) of a book. Django will call views.book_detail(request, pk=25).
  • path('books/<str:genre>/', views.books_by_genre): This pattern matches /books/crime/, where crime is a string representing the genre of books. Django will call views.books_by_genre(request, genre="crime").
  • path('books/', views.book_index): This pattern matches /books/, which lists all books. Django will call views.book_index(request).

Example: How Django URLs Work — Basic HTML Pages & Navigation

1. Define views in views.py:

Python
from django.http import HttpResponse
from django.shortcuts import render

def home_view(request):
    return render(request, 'home.html')

def about_view(request):
    return render(request, 'about.html')

def contact_view(request):
    return render(request, 'contact.html')

2. Create basic templates in your templates/ folder:

home.html:

HTML
<h1>Home Page</h1>
<p>Welcome to the home page.</p>
<a href="/about/">Go to About</a><br>
<a href="/contact/">Go to Contact</a>

about.html:

Python
<h1>About Page</h1>
<p>This is the about page.</p>
<a href="/">Go to Home</a><br>
<a href="/contact/">Go to Contact</a>

contact.html:

HTML
<h1>Contact Page</h1>
<p>Contact us at [email protected].</p>
<a href="/">Go to Home</a><br>
<a href="/about/">Go to About</a>

3. Define URL patterns in urls.py:

Python
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home_view, name='home'),
    path('about/', views.about_view, name='about'),
    path('contact/', views.contact_view, name='contact'),
]

Output:

1. Home Page:

HomePageDjangoApp
Home Page

2. Click “Go to About”:

AboutPageDjangoApp
About Page

3. Click “Go to Contact”:

ContactPageDjangoApp
Contact Page

Path Converters

In Django, path converters are used in URL patterns to capture specific values from the URL and pass them to the view as arguments. For example:

  • int – Matches zero or any positive integer.
  • str – Matches any non-empty string, excluding the path separator(‘/’).
  • slug – Matches any slug string, i.e. a string consisting of alphabets, digits, hyphen and under score.
  • path – Matches any non-empty string including the path separator(‘/’)
  • uuid – Matches a UUID(universal unique identifier).

Next Article
Practice Tags :

Similar Reads