Open In App

Django URLs

Last Updated : 28 Oct, 2025
Comments
Improve
Suggest changes
6 Likes
Like
Report

In Django, views are Python functions or classes that handle HTTP requests and return HTTP responses. To make views accessible through specific URLs, Django uses a URL configuration system known as URLConf. This system maps URL patterns to corresponding views, enabling precise request routing.

django_urls

Understanding URLConf in Django

URLConf directs incoming requests to the appropriate view based on defined URL patterns.

  • ROOT_URLCONF in settings.py specifies the root URL configuration module (usually project_name.urls).
  • Each URLConf module defines a variable urlpatterns, which is a list of URL patterns.
  • URL patterns are evaluated in order, the first match invokes its corresponding view.
  • If no pattern matches, Django triggers the default error handler (e.g., 404).

Structure of URLConf

URLConf modules organize URL patterns for both project-level and app-level routing.

  • Use path() to map a URL pattern to a view.
  • include() allows inclusion of app-specific URL configurations, keeping the project modular.

Example: project-level urls.py

Python
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('books.urls')),
]

In the above example:

  • path('admin/', admin.site.urls) maps /admin/ to the Django admin interface.
  • path('', include('books.urls')) delegates URL matching to the books app.

URL Patterns in Django

URL patterns define the routes Django uses to match incoming HTTP requests to views.

  • URL patterns are stored in the urlpatterns list in a URLConf module.
  • Each entry in urlpatterns typically uses the path() function to associate a URL pattern with a view.
  • Dynamic parts of a URL can be captured using path converters and passed as arguments to views.
  • Using the name argument in a path allows reverse URL resolution, useful in templates and views.

Example: urls.py for a books app

Python
from django.urls import path
from . import views

urlpatterns = [
    path('books/<int:pk>/', views.book_detail, name='book_detail'),
    path('books/<str:genre>/', views.books_by_genre, name='books_by_genre'),
    path('books/', views.book_index, name='book_index'),
]

In the above example:

  • path('books/<int:pk>/') captures an integer pk for a book detail view.
  • path('books/<str:genre>/') captures a string genre for filtering books by genre.
  • path('books/') matches the book listing page.
  • Using name='...' allows references in templates using {% url 'name' %} and in Python code using reverse().

Example: Basic Django URL Routing with HTML Pages

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 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 contact@example.com.</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

Path converters capture dynamic values from URLs and pass them as arguments to views. They are specified inside angle brackets < > in URL patterns.

  • int: matches any integer (0 or positive) and converts it to a Python int.
  • str: matches any non-empty string excluding the path separator /.
  • slug: matches letters, numbers, hyphens, and underscores, suitable for readable URLs.
  • path: matches any non-empty string, including the path separator /.
  • uuid: matches a valid UUID string and converts it to a Python UUID object.

Example:

Python
from django.urls import path
from . import views

urlpatterns = [
    path('books/<int:pk>/', views.book_detail, name='book_detail'),
    path('books/<str:genre>/', views.books_by_genre, name='books_by_genre'),
    path('books/<slug:slug>/', views.book_by_slug, name='book_by_slug'),
]

In the above example:

  • <int:pk> passes an integer primary key to the view.
  • <str:genre> passes a string representing the book genre.
  • <slug:slug> passes a slug string for human-readable URLs.
Suggested Quiz
5 Questions

In a Django project, which setting defines the module that contains URL patterns for incoming requests?

  • A

    URLPATTERN_CONF

  • B

    MAIN_URL_MODULE

  • C

    DEFAULT_URLS

  • D

    ROOT_URLCONF

Explanation:

ROOT_URLCONF points to the module (usually project_name/urls.py) where the urlpatterns list is defined.

What is stored in the urlpatterns list inside a Django urls.py file?

  • A

    View-class definitions

  • B

    Path or re_path entries mapping URLs to views

  • C

    Model definitions

  • D

    HTTP request objects

Explanation:

Each entry in urlpatterns defines a pattern and the view to handle requests matching that pattern.

What does the include() function do when used inside a Django project's urls.py?

  • A

    It imports all models from another app

  • B

    It merges two view files together

  • C

    It automatically creates URL patterns for all views

  • D

    It includes URL patterns defined in another module or app’s urls.py

Explanation:

include() allows modular URL configuration by delegating part of the URL routing to another urls.py inside an app.

In Django, what happens when a request URL does not match any pattern in urlpatterns?

  • A

    Django calls the default error handler, usually returning a 404 page

  • B

    Django returns a 500 Internal Server Error

  • C

    Django redirects to home page

  • D

    Django repeats the matching process

Explanation:

If no URL pattern matches, Django triggers its default error-handling mechanism resulting in a 404 (page not found).

What feature does using the name argument in a path() call provide in Django URL patterns?

  • A

    Automatic view generation

  • B

    Ability to reverse URLs by name in templates and code instead of hard-coding paths

  • C

    Enforces trailing slash in URL

  • D

    Encrypts the URL parameters

Explanation:

Named URL patterns allow developers to use {% url 'name' %} in templates or reverse('name') in Python code, making URL references more maintainable.

Quiz Completed Successfully
Your Score :   2/5
Accuracy :  0%
Login to View Explanation
1/5 1/5 < Previous Next >

Explore