INT253Semester 7 • 3 CreditsElective Subjects

Web Development In Python Using Django

This course develops skills in building web applications with Python and Django, including project and app structure, views, URL mapping, templates, forms, models, migrations, ORM, and Django Admin. It also covers cookies, sessions, authentication, user management, permissions, testing, debugging, and database configuration.

6 Units • Notes • Model Answers • MCQs
Select Course Unit (6 Units)
Active: Unit 1
Unit 1:Unit 1: Introduction to Django
7 min read•High-Yield Unit Guide

Unit 1: Introduction to Django

Unit 1 Exam Focus & Core Takeaways

Review the core definitions, standard architectures, and syntax patterns below. Pay special attention to sections highlighted with bullet points for your mid-term and end-term subjective questions.

Unit 1: Introduction to Django

1. Introduction: The Framework and Its Governing Philosophy

Django is a high-level, open-source Python web framework designed to encourage rapid development, clean pragmatic design, and enterprise-grade reliability. Conceived in a fast-paced newspaper newsroom (the Lawrence Journal-World) in 2003 and released open-source in 2005, Django was engineered to handle complex database-driven web applications under aggressive deadlines.

Django is anchored upon several fundamental software engineering principles:

  1. "Batteries-Included" Philosophy: Django provides out-of-the-box implementations for common web development challenges—an Object-Relational Mapper (ORM), an automated administrative interface (django.contrib.admin), user authentication and session management (django.contrib.auth), form handling and validation, CSRF/XSS protection, and internationalization. Developers rarely need to stitch together fragmented third-party libraries for core functionality.
  2. Don't Repeat Yourself (DRY): Every distinct piece of knowledge or logic must have a single, unambiguous, authoritative representation within a system. For instance, data models are defined strictly once in models.py; from this single definition, Django automatically derives database schemas, migrations, form fields, and administrative interfaces.
  3. Model-Template-View (MTV) Architectural Pattern: Django separates concerns using an adaptation of the classic Model-View-Controller (MVC) paradigm:
    • Model (MM): The data access layer. Encapsulates business logic, data structures, fields, and database interactions via the Django ORM.
    • Template (TT): The presentation layer. Governs how data is rendered for the user (HTML, XML, JSON) using the Django Template Language (DTL). Corresponds to the classic MVC View.
    • View (VV): The execution and routing layer. Accepts HTTP requests, interacts with Models, applies business logic, and selects/renders the appropriate Template. Corresponds to the classic MVC Controller.
  4. Explicit Over Implicit & Loose Coupling: Components across the framework (e.g., the template system, database layer, routing engine) are intentionally decoupled. Developers can swap out default components (such as replacing the Django Template Engine with Jinja2) without disrupting remaining subsystems.
CODE
+-----------------------------------------------------------------------------------+
|                        DJANGO ARCHITECTURAL REQUEST FLOW (MTV)                    |
+-----------------------------------------------------------------------------------+
                                          |
                                HTTP Request from Client
                                          |
                                          v
                              +-----------------------+
                              |   URLconf (urls.py)   |
                              | - Regex / Path Match  |
                              +-----------------------+
                                          |
                                          | Dispatches request to target View
                                          v
                              +-----------------------+
                              |    View (views.py)    | <==== Business Logic
                              +-----------------------+
                                     /         \
                 Queries / Modifies /           \ Injects context dictionary
                                   /             \
                                  v               v
            +-----------------------+   +-----------------------+
            |    Model (models.py)  |   | Template (templates/) |
            | - Database / ORM      |   | - HTML / DTL Tags     |
            +-----------------------+   +-----------------------+
                                                  |
                                          Renders final HTML
                                                  |
                                                  v
                                      HTTP Response to Client

2. Environment Setup, Python Virtual Environments, and Installation

Professional Python development demands strict isolation of dependencies to prevent package version collisions between disparate projects.

2.1 The Role of Virtual Environments

When packages are installed via standard pip install <package>, they are placed into the operating system's global Python site-packages directory. If Project A requires Django==4.2 while Project B depends on Django==5.0, global installations produce dependency conflicts.

  • venv Module: Standard library module in Python 3 that creates lightweight, self-contained virtual environments with isolated directory trees containing their own Python interpreter binaries, standard library copies, and dedicated site-packages.

Virtual Environment Creation and Lifecycle Workflow:

bash
# 1. Create a dedicated project workspace directory
mkdir my_django_workspace
cd my_django_workspace

# 2. Instantiate a virtual environment named '.venv' or 'env'
python -m venv .venv

# 3. Activate the virtual environment
# On Windows (PowerShell):
.venv\Scripts\Activate.ps1
# On Windows (Command Prompt):
.venv\Scripts\activate.bat
# On Linux / macOS:
source .venv/bin/activate

# 4. Verify that the virtual environment interpreter is active
where python   # Windows
which python   # Linux / macOS

# 5. Upgrade pip and install Django
python -m pip install --upgrade pip
pip install django

# 6. Verify Django installation and version
python -m django --version

2.2 Editor and IDE Configuration

  1. Visual Studio Code (VS Code):
    • Install the official Microsoft Python extension.
    • Set the workspace interpreter via Command Palette (Ctrl+Shift+P -> Python: Select Interpreter) pointing explicitly to .venv\Scripts\python.exe.
    • Install Django syntax highlighting extensions for .html templates.
  2. PyCharm:
    • PyCharm Professional includes native Django project scaffolding, integrated database visualizers, and visual template debugging.
    • Configure project interpreter under Settings -> Project -> Python Interpreter pointing to the virtual environment.

3. Conceptual Foundation: Projects vs. Applications

A foundational architectural concept in Django is the strict distinction between a Project and an App:

Architectural DimensionDjango ProjectDjango Application (App)
DefinitionA complete web site, deployment container, or system instance. It encompasses global configurations, database connections, and middleware.A modular, self-contained Python package that delivers a specific, focused functional capability.
Scope & MultiplicityOne project per website / deployment. Composed of multiple integrated apps.Many apps per project. An app can be plugged into multiple different projects without modification.
Primary Artifactssettings.py, root urls.py, wsgi.py, asgi.py, manage.py.models.py, views.py, apps.py, admin.py, tests.py, migrations folder.
Examplesecommerce_platform, university_portal, hospital_system.cart, catalog, accounts, billing, blog, feedback.
Portability PrincipleProject configuration is environment-specific and rarely distributed as a standalone package.Apps should adhere to the "pluggable app" pattern, packaged cleanly to be shared via PyPI.

4. Creating Your First Project and Project Anatomy

A Django project is instantiated using the django-admin command-line utility.

4.1 Project Creation Command

bash
django-admin startproject config .

Best Practice Tip: Appending the trailing dot (.) instructs Django to create the configuration package directly within the current directory rather than generating an unnecessary nested root directory (avoiding config/config/settings.py).

4.2 File-by-File Anatomy of a Project

Upon executing startproject, Django scaffolds the following structure:

CODE
my_django_workspace/
│
├── manage.py                     # Command-line utility for project interaction
│
└── config/                       # Project configuration package
    ├── __init__.py               # Marks directory as a Python package
    ├── settings.py               # Central configuration settings
    ├── urls.py                   # Root URL declarations (URL routing table)
    ├── asgi.py                   # Entry point for ASGI-compatible web servers
    └── wsgi.py                   # Entry point for WSGI-compatible web servers

Detailed File Descriptions:

  1. manage.py:
    • A thin wrapper script around django.core.management.
    • Automatically injects the project's settings.py module path into the DJANGO_SETTINGS_MODULE environment variable and delegates command execution to execute_from_command_line().
    • Rule: Never edit manage.py directly under standard workflows.
  2. config/__init__.py:
    • An empty file that signifies to Python that config/ must be treated as an importable module package.
  3. config/settings.py:
    • The central configuration database for the entire project. Contains uppercase configuration constants:
      • BASE_DIR: Pathlib object resolving the absolute filesystem root path of the project.
      • SECRET_KEY: Cryptographic salt utilized for session signing, CSRF tokens, and password reset hashes. Must be kept strictly secret in production environments.
      • DEBUG: Boolean flag (True or False). In development (DEBUG=True), detailed traceback error pages are displayed upon exceptions, and static files are served automatically. Must be set to False in production, or internal environment variables and code snippets will be exposed to attackers upon exceptions.
      • ALLOWED_HOSTS: List of domain names or IP addresses that the Django site can serve (protects against HTTP Host Header attacks).
      • INSTALLED_APPS: List of strings designating all active Django applications enabled for this project instance.
      • MIDDLEWARE: List of processing hooks executed sequentially during the request/response lifecycle.
      • ROOT_URLCONF: String path pointing to the root URLconf module (config.urls).
      • TEMPLATES: Configuration dictionary governing template engines, directories (DIRS), and context processors.
      • DATABASES: Dictionary defining database engine backends (django.db.backends.sqlite3, postgresql, mysql), database credentials, host, and port.
      • AUTH_PASSWORD_VALIDATORS: Set of rules validating user password complexity.
      • LANGUAGE_CODE & TIME_ZONE: Localization constants (e.g., 'en-us', 'UTC', 'Asia/Kolkata').
      • STATIC_URL: The URL prefix used to serve static files (/static/).
  4. config/urls.py:
    • The root routing table (URL dispatcher). Contains the urlpatterns list matching incoming HTTP request paths to callable view functions or included app URLconfs.
  5. config/wsgi.py:
    • Web Server Gateway Interface entry point. Connects synchronous WSGI-compliant production web servers (such as Gunicorn, uWSGI, or Apache mod_wsgi) to the Django application callable.
  6. config/asgi.py:
    • Asynchronous Server Gateway Interface entry point. Connects asynchronous ASGI-compliant servers (such as Daphne or Uvicorn) to handle WebSockets, HTTP/2, and async views.

5. Command-Line Utilities: django-admin vs. manage.py

Django provides two command-line utilities that share the same underlying command dispatcher but differ in environmental awareness:

Feature / Aspectdjango-adminmanage.py
Environment AwarenessSystem-wide tool. Unaware of any specific project's settings.py unless explicitly passed via --settings flag or setting DJANGO_SETTINGS_MODULE.Local project script. Automatically configures DJANGO_SETTINGS_MODULE to the current project's settings module.
Typical UsageInitial project bootstrapping (django-admin startproject <name>).Daily project operations (runserver, migrate, makemigrations, createsuperuser, shell).
Invocationdjango-admin <command> [options]python manage.py <command> [options]

5.1 Primary Management Commands Reference

  • runserver:
    • Starts the lightweight, single-threaded development HTTP server on 127.0.0.1:8000 (can bind to custom ports/IPs: python manage.py runserver 0.0.0.0:8080).
    • Features Auto-Reloading: Automatically detects code changes and restarts the server process.
    • Warning: Strictly designed for local development; never use runserver in production.
  • startapp <app_name>:
    • Generates the standard directory skeleton for a new Django application.
  • makemigrations:
    • Inspects models.py across all installed apps, detects structural changes (new models, altered fields, modified constraints), and writes executable migration scripts into each app's migrations/ directory.
  • migrate:
    • Executes unapplied migration scripts against the configured database, synchronizing database tables and column definitions with data models.
  • createsuperuser:
    • Prompts interactively to create an administrative user account with is_superuser=True and is_staff=True in the auth_user table.
  • shell:
    • Launches an interactive Python REPL with the complete Django project environment and database connections pre-initialized.
  • check:
    • Uses the System Check Framework to scan the entire project codebase for common configuration errors, invalid model relationships, and security misconfigurations.
  • collectstatic:
    • Gathers static files from across all installed apps into the single centralized directory defined by STATIC_ROOT for production deployment.

6. Creating and Registering a Django Application

Applications provide modularity, encapsulating specific domain models and presentation logic.

6.1 Creating the App Skeleton

To create an application named courses:

bash
python manage.py startapp courses

6.2 Anatomy of an App Package

The startapp command generates the following files:

CODE
courses/
│
├── __init__.py               # Marks directory as an importable Python package
├── admin.py                  # Registers models with the Django Admin site
├── apps.py                   # Application-specific configuration class
├── models.py                 # Data models defining database schemas (ORM)
├── tests.py                  # Unit and integration test suites
├── views.py                  # HTTP request handlers (function or class-based)
└── migrations/               # Stores database schema migration history files
    └── __init__.py

File-by-File Breakdown:

  1. apps.py:
    • Contains the application configuration subclassing django.apps.AppConfig:
      python
      from django.apps import AppConfig
      
      class CoursesConfig(AppConfig):
          default_auto_field = 'django.db.models.BigAutoField'
          name = 'courses'
      
    • Allows configuration of application metadata, human-readable names, and registration of initialization signals.
  2. models.py:
    • Defines database tables as Python classes inheriting from django.db.models.Model.
    • Each attribute represents a database column (e.g., CharField, IntegerField, ForeignKey).
  3. views.py:
    • Contains request-handling functions or classes. Each view accepts an HttpRequest object as its first argument and must return an HttpResponse object (or raise an exception).
  4. admin.py:
    • Registers models with admin.site.register(MyModel) to make them editable within the automated administrative dashboard.
  5. tests.py:
    • Houses automated test cases subclassing django.test.TestCase.
  6. migrations/:
    • A directory containing timestamped Python scripts generated by makemigrations that record incremental changes to database schemas over time.

6.3 Registering the App in settings.py

Creating an app directory via startapp does not automatically enable it. Django completely ignores the app until it is explicitly registered in the INSTALLED_APPS list in config/settings.py.

Registration Approaches:

python
# config/settings.py

INSTALLED_APPS = [
    # Built-in Core Django Apps:
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Third-Party Apps (e.g., rest_framework, crispy_forms)

    # Local Project Apps:
    # Recommended Best Practice (Referencing AppConfig path):
    'courses.apps.CoursesConfig',

    # Shorthand (Acceptable for simple apps):
    # 'courses',
]

Best Practice: Referencing 'courses.apps.CoursesConfig' is preferred because it ensures any custom configuration, signal wiring, or metadata defined in AppConfig.ready() is properly executed during application startup.


7. The Development Server: Mechanics and Precautions

When executing python manage.py runserver, Django initiates a development environment optimized for developer productivity:

  1. System Check Framework: Scans the project for errors prior to listening for connections.
  2. Migration Warning: Alerts the developer if unapplied database migrations exist.
  3. StatReloader: A file-watching thread that monitors all .py, .html, and .json files. When a file modification is saved to disk, the reloader restarts the server process automatically, reloading code changes instantly.
  4. Threaded Architecture: By default, runserver runs with multi-threading enabled to handle concurrent browser requests (such as simultaneous CSS and image requests).

Critical Security Warning for Production:

The built-in development server has not undergone security audits and is not optimized for performance, concurrency, or resilience:

  • It serves static media slowly and in-memory.
  • It can be easily overwhelmed by denial-of-service (DoS) attacks.
  • In production, deployments must use a production WSGI/ASGI server (e.g., Gunicorn or Uvicorn) behind a reverse proxy (e.g., NGINX) to handle SSL termination, buffering, and static asset serving.

8. Summary of Essential Commands and Workflow

CODE
                  +-----------------------------------+
                  |   django-admin startproject mysite|
                  +-----------------------------------+
                                    |
                                    v
                  +-----------------------------------+
                  |     cd mysite                     |
                  |     python manage.py startapp blog|
                  +-----------------------------------+
                                    |
                                    v
                  +-----------------------------------+
                  | Register in settings.py:          |
                  | INSTALLED_APPS += ['blog.apps...']|
                  +-----------------------------------+
                                    |
                                    v
                  +-----------------------------------+
                  | Define data models in models.py   |
                  +-----------------------------------+
                                    |
                                    v
                  +-----------------------------------+
                  | python manage.py makemigrations   |
                  | python manage.py migrate          |
                  +-----------------------------------+
                                    |
                                    v
                  +-----------------------------------+
                  | python manage.py createsuperuser  |
                  | python manage.py runserver        |
                  +-----------------------------------+