How URL dispatching works in Django project?

In a Django project, URL dispatching is the process of mapping URLs to corresponding views. When a user sends a request to a Django application, Django uses a URL dispatcher to determine which view function or class-based view should handle the request based on the URL pattern.

How it Works – Step by Step:

  1. User sends a request (e.g., https://example.com/about/)
  2. Django checks the urlpatterns defined in the main urls.py file (usually inside the project folder).
  3. If matched, it dispatches the request to the corresponding view function.
  4. The view function processes the request and returns an HTTP response.

Let us create a django project myproject or testproject or myshop

  1. Create a directory myshop
  2. In the windows command prompt in C or D drive enter mkdir myshop
  3. cd myshop
  4. Create a virtual envirnment
  5. python -m venv myshop_env
  6. Activate virtual environment
  7. myshop\scripts\activate
  8. After activating a virtual environment install Django
  9. pip install django
  10. Now create a django project
  11. I use the project name core (you can use myshop or any other name)

Create a django project using the command:

django startproject core . (type dot at the end)

The following directory structure is created

myshop/
│── manage.py
│── core/  # Main project package
│   │── __init__.py
│   │── settings.py
│   │── urls.py
│   │── asgi.py
│   └── wsgi.py

1. manage.py

A command-line tool to run the Django project.

Used for running the server, creating apps, applying migrations, managing users, etc.

Example commands:

python manage.py runserver # Start the development server
python manage.py makemigrations # Create migration files
python manage.py migrate # Apply migrations to the database
python manage.py createsuperuser # Create an admin user

2. myshop/ (Main Project Folder)

a) __init__.py

An empty file that tells Python to treat this directory as a package.

A module is simply a Python file (.py) that contains functions, classes, or variables. It allows code to be logically organized.
A package is a directory that contains a collection of modules and a special file named __init__.py (can be empty). It allows you to organize related modules together.

b) settings.py

  • Main configuration file for the Django project.
  • Contains settings for:
    • Database Configuration (DATABASES)
    • Installed Apps (INSTALLED_APPS)
    • Middleware (MIDDLEWARE)
    • Templates Configuration (TEMPLATES)
    • Static and Media Files (STATIC_URL, MEDIA_URL)
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',   
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'core.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',        
        'DIRS': 
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

In the TEMPLATES add a value for the dictionary key ‘DIRS:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',        
        'DIRS': [BASE_DIR/'templates'], #Added by VBhat on 15/04/2025
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Create a folder templates (to store html files) under myshop folder

Now the directory structure is as follows:

myshop/
│── manage.py
│── templates (Django template files, html files are stored in this directory)
│── core/ # Main project package
│ │── __init__.py
│ │── settings.py
│ │── urls.py
│ │── asgi.py
│ └── wsgi.py

c) urls.py

  • Defines URL routing patterns for the project.
from django.contrib import admin
from django.urls import path
urlpatterns = [
    path('admin/', admin.site.urls),]

d) asgi.py & wsgi.py

  • wsgi.py: Entry point for WSGI applications. Used for deploying Django projects on production servers. (WSGI servers e.g., Gunicorn, uWSGI))
  • asgi.py: Entry point for ASGI applications for async operations (WebSockets, real-time applications)..

Now create a Django application using the following command:

python manage.py startapp testapp

The directory structure is updated as follows:

myshop/
│── manage.py
│── templates (Django template files, html files are stored in this directory)
│── core/  # Main project package
│   │── __init__.py
│   │── settings.py
│   │── urls.py
│   │── asgi.py
│   └── wsgi.py

└── testapp/  (Created when running `startapp`)
    │── migrations/
    │── __init__.py
    │── admin.py
    │── apps.py
    │── models.py
    │── tests.py
    │── views.py
    │── tests.py    

Create and apply migrations using the following commands

python manage.py makemigrations myapp
python manage.py migrate

This will create migration files in the created app also create database tables for the modes defined in the django applications

Create urls.py file under testapp

Create a templates directory under testapp and test directory under template directory

This is to store application specific html template files.

Now the directory structure is as follows:

myshop/
│── manage.py
│── templates (Django template files html files are stored in this directory)
│── db.sqlite3 (sqlite database file)
│── myproject/  # Main project package
│   │── __init__.py
│   │── settings.py
│   │── urls.py
│   │── asgi.py
│   └── wsgi.py

└── testapp/  (Created when running `startapp`)
    │── migrations/
    │── __init__.py
    │── admin.py
    │── apps.py
    │── models.py 
    │── tests.py
    │── views.py (view functions are added in this file)
    │── tests.py
    │── templates/test (To store application specific html template files)
    └── urls.py  (Manually created for app-specific routes)

3. db.sqlite3 (Database)

  • Default SQLite database file.
  • You can use PostgreSQL, MySQL, or other databases in settings.py, corresponding database engine has to be added in settings.py file

Each Django project can have multiple apps, each responsible for a specific functionality and an app has its own structure

4. testapp/ (Django App)

We have created django application “testapp” has its own structure:

  • migrations/ → Stores database migration files (generated by makemigrations)..
  • models.py → Defines the database models (tables) using Django ORM
  • views.py → Contains logic for handling user requests and handles the logic for rendering webpages.
  • urls.py (manually created) → Defines URLs specific to the app.
  • admin.py → Registers models for Django’s admin panel.
  • apps.py → Defines configuration for the app.
  • tests.py → Contains test cases for the app.
  • templates/ (HTML Files) Stores HTML templates for rendering dynamic webpages.

Update urls.py (project specific mail url file) file in the myshop directory as follows:

myshop/urls.py (Main URL Configuration)

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

urlpatterns = [
    path('admin/', admin.site.urls),
    # For every django application add a path to include a application specific urls
    path('', include('testapp.urls')), # Delegates to app's URL config
    ]

Update urls.py file in testapp directory

testapp/urls.py (App URL Configuration)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('about/', views.about, name='about'),
]

Update views.py file in testapp

testapp/views.py

from django.http import HttpResponse

def home(request):
   return HttpResponse("Welcome to the Home Page!")

def about(request):
  return HttpResponse("This is the About Page.")

In the command prompt run the development server using the command:

python manage.py runserver

(myshop_env) D:\django\myshop>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
April 18, 2025 - 16:22:03
Django version 5.2, using settings 'core.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

WARNING: This is a development server. Do not use it in a production setting. Use a production WSGI or ASGI server instead.
For more information on production servers see: https://docs.djangoproject.com/en/5.2/howto/deployment/

How URL Dispatching Works ?

  1. In a web browser (chrome or edge) type http://127.0.0.1/about/
  2. Django looks at myshop/urls.py and includes urls from testapp.
  3. It then checks testapp/urls.py and finds path('about/', views.about)
  4. It calls the about view function, which returns an HttpResponse
  5. In the browser you will see “This is the About Page.”

Now let us add few more URL patterns

#testapp/urls.py (App URL Configuration)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('about/', views.about, name='about'),
    path('greet/<str:name>/', views.greet_user, name='greet'),
    path('wish/<str:name>/',views.wish_user, name='wish'),
]

Add a view function (greet) in views.py file

#testapp/views.py


from django.http import HttpResponse

def home(request):
     return HttpResponse("Welcome to the Home Page!")

def about_user(request):
    return HttpResponse("This is the About Page.")

def greet_user(request, name):
    return HttpResponse(f"Namaskara, {name}!")

def wish_user(request, name):
    context = {"name": name}
    print("context", context)
    return render(request, 'test/test1.html',context)               
 

In the testapp under templates/test directory, create a test1.html file

└── testapp/  (Created when running `startapp`)
    │── migrations/
    │── __init__.py
    │── admin.py
    │── apps.py
    │── models.py 
    │── tests.py
    │── views.py (view functions are added in this file)
    │── tests.py
    │── templates/test/
    └── urls.py  (Manually created for app-specific routes)

testapp/tesmplates/test/test1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {% if name %}
    
    <h1> Namaskara {{name}} !, How are you?</h1> 
    {% else %}  
    <h1> Namaskara! How are you?</h1> 
    {% endif %}

</body>
</html>

How URL Dispatching Works?

  1. In a web browser (chrome or edge) type http://127.0.0.1/greet/Rama/
  2. Django looks at myshop/urls.py and includes urls from testapp.
  3. It then checks testapp/urls.py and finds path('greet/', views.greet_user)
  4. It calls the greet_user view function, which returns an HttpResponse (Rama)
  5. In the browser you will see “Namaskara Rama.”
  1. In a web browser (chrome or edge) type http://127.0.0.1/wish/Rama/
  2. Django looks at myshop/urls.py and includes urls from testapp.
  3. It then checks testapp/urls.py and finds path('wish/', views.wish_user)
  4. It calls the wish_user view function, which returns test1.html with context
  5. test1.html is a django template file, django checks if name exists if it exists places value of name in the {{name}} and passes “Namaskara Rama!, How are you?” to the browser, if name do not exist then “Namaskara!, How are you?” is passed to the browser.
  6. In the browser you will see “Namaskara Rama !, How are You?”

Try yourself: Add more url patters, create view functions, create html file

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *