Django Web Framework - Complete Setup Guide

Version: 3.0 | Last Updated: February 25, 2026


Module 1: Django Setup

1.1 Python Setup

Step 1: Install Python (Recommended: 3.10 to 3.13)

You can install multiple Python versions on the same system. If you already have Python installed, use the py launcher to install another version alongside it:

py install 3.13

Step 2: Create a Virtual Environment

Virtual environments create isolated Python environments for your projects:

python -m venv env

To create an environment with a specific Python version:

python3.13 -m venv env313

Step 3: Activate the Virtual Environment (Windows)

env\Scripts\activate
Note: After activation, you should see (env) in your terminal prompt, indicating the virtual environment is active.

Step 4: Deactivate the Virtual Environment

When you're done working on your project, deactivate the virtual environment:

deactivate
Tip: You can reactivate the environment anytime by running the activate command again. Always ensure your virtual environment is activated before installing packages or running Django commands.

1.2 Django Project Creation

Step 1: Install Django

Check if Django is installed; if not, install it using pip:

pip install django

Step 2: Create a Django Project

django-admin startproject project_name

Replace project_name with your desired project name (e.g., mywebsite, myproject).

Step 3: Create a Django App

python manage.py startapp app_name
App Purpose Description
Blog Handles blog posts, comments, and categories
Shop Manages products, cart, and orders
User Accounts Handles user registration, login, and profiles
Important: Each app handles a specific functionality of your project. You will write models, views, and templates inside the app to build your project features.

Step 4: Run the Development Server

python manage.py runserver
Note: This starts a local server at http://127.0.0.1:8000/. The server automatically reloads when you make changes to your code, making development easier.

Module 2: Project and App Structure

2.1 Views and URLs Configuration

Step 1: Create URLs File in App

In your app folder, create a file named urls.py:

yourapp/
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── models.py
    ├── tests.py
    ├── urls.py      <-- Create this file
    └── views.py
    

Step 2: Write Views

In yourapp/views.py, create your views:

from django.http import HttpResponse

def index(request):
    return HttpResponse("<h1>Hello, this is the index page of myApp!</h1>")

def blog(request):
    return HttpResponse("<h1>Welcome to the Blog Page</h1>")

def about(request):
    return HttpResponse("<h1>About Us</h1><p>This is our company information.</p>")
    
Note: We use HttpResponse for testing. Normally, we use render() to return templates with HTML files.

Step 3: Configure App URLs

In yourapp/urls.py, set up the URL patterns:

from django.urls import path
from . import views

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

Step 4: Include App URLs in Project

In your project's main urls.py file:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('yourapp.urls')),  # Connect your app URLs to the project
]
    
Important Note about URL Routing: This goes to your app's urls.py to get its paths. The '' in the project's urls.py means the paths start at the root, so blog becomes http://127.0.0.1:8000/blog/. If you used 'home/' in project's urls.py, the paths would start at http://127.0.0.1:8000/home/. Test it then you will understand.

Step 5: Run Server and View Your Pages

Now run the development server to see your pages in action:

python manage.py runserver

Open your browser and visit these URLs:

Module 3: Models and Database

3.1 Adding Your App to INSTALLED_APPS

Purpose: Enables Models, Templates, and Features

  1. Go to your project folder and open settings.py.
  2. Find the INSTALLED_APPS list.
  3. Add your app name at the end of the list, like 'myapp',.
What it does? This tells Django about your app so it can use its models, templates, and other features.

3.2 Creating Models

Purpose: Defining Tables in the Database

  1. Go to your app folder. Open models.py.
  2. Write your models as Python classes. Each class represents a table, and each attribute is a column.

Example Model:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.name
    
Why? Models define what data your app will store and how it will be organized in database tables.

After creating or changing models, run migrations:

python manage.py makemigrations

This tells Django that something has changed in the models.

python manage.py migrate

This updates those changes in the database.

3.3 How to Use Parameters in URLs

Purpose of Parameters:

Parameters are used to identify and access a specific resource (such as a single product, user, or post) for CRUD operations (Create, Read, Update, Delete).

Step 1: Define URL with Parameter

Go to your app's urls.py file. Pass parameters in the URLs where you want to use them:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('product/<int:id>/', views.product_detail, name='product_detail'),
    path('category/<str:category_name>/', views.category_products, name='category_products'),
]
    
Parameter Type Example Description
<int:id> /product/5/ Matches an integer and passes it as 'id'
<str:name> /category/electronics/ Matches a string and passes it as 'name'
<slug:slug> /post/my-first-post/ Matches a slug (letters, numbers, hyphens)

Step 2: Use Parameter in View

Go to your app's views.py file. Import your models and use the parameter to retrieve specific data:

from django.http import HttpResponse
from .models import Product

def product_detail(request, id):
    # Use the parameter to find a matching product
    try:
        product = Product.objects.get(id=id)
        return HttpResponse(f"<h1>{product.name}</h1><p>Price: ${product.price}</p>")
    except Product.DoesNotExist:
        return HttpResponse("<h1>Product not found</h1>")

def category_products(request, category_name):
    # Find all products in a category
    products = Product.objects.filter(category=category_name)
    return HttpResponse(f"<h1>Products in {category_name}</h1><p>Found {products.count()} products</p>")
    
Mental Map: One table for all data, one page (view), but to show a different row each time, we use parameters that match a column to get its specific row. Think of it like looking up a word in a dictionary - the parameter is the word you're searching for, and the view returns its definition.

3.4 Creating a Superuser for Admin Panel

  1. Run the createsuperuser command:
    python manage.py createsuperuser
  2. Provide the required information when prompted:
    • Username (required)
    • Email address (optional - press Enter to skip)
    • Password (required - characters won't show while typing)
  3. Run the development server:
    python manage.py runserver
  4. Access the admin panel:

    Open your browser and go to http://127.0.0.1:8000/admin/ (remember the admin path we already have in project/urls.py)

  5. Log in with the username and password you just created.
What you'll see: After logging in, you will see the admin dashboard. By default, you will already see a table named Users (for authentication and user management).

From the admin panel, you can:

3.5 Registering Models in admin.py

  1. Go to the admin.py file in your app.
  2. Import the models you want to register.
  3. Register them using admin.site.register().

Example admin.py:

from django.contrib import admin
from .models import Product  # Import your model

# Register your models here
admin.site.register(Product)
    
After registering: Go to the admin panel and refresh the page. You will now see your registered tables in the admin dashboard alongside the Users table. You can now add, edit, and delete records through the admin interface.

Module 4: Templates

4.1 What are Templates?

Templates in Django are HTML files that can include dynamic content. They allow you to separate presentation (frontend) from logic (backend).

Why use templates?

Benefits you get:

4.2 Creating Template Structure

Step 1: Create a templates folder

Inside your Django app, create a folder named templates. You can organize multiple HTML files here.

Step 2: Create the folder structure

yourapp/ ├── templates/ │ ├── base.html │ ├── pages/ │ │ ├── home.html │ │ └── about.html │ └── components/ │ ├── header.html │ ├── footer.html │ └── button.html ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── urls.py └── views.py
Note: This is the recommended folder structure for templates. It keeps your code organized and maintainable.

4.3 Creating Components and Using Blocks (Slots)

Components are reusable HTML parts (like header/footer).
Blocks (or slots) are placeholders for dynamic content that child templates can fill.

base.html - The Main Layout

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}My Site{% endblock %}</title> </head> <body> <!-- Header component --> {% include 'components/header.html' %} <!-- Main content with block (slot) --> <div class="content"> {% block content %}{% endblock %} </div> <!-- Footer component --> {% include 'components/footer.html' %} </body> </html>

components/header.html

<header> <h1>My Website Header</h1> <nav> <a href="/">Home</a> | <a href="/about/">About</a> </nav> </header>

components/footer.html

<footer> <p>© 2026 My Website</p> </footer>

pages/home.html - Child Template

{% extends 'base.html' %} {% block title %}Home - My Site{% endblock %} {% block content %} <h2>Welcome to My Site!</h2> <p>This is dynamically rendered content using Django templates.</p> {% endblock %}

4.4 Rendering Templates in Views

Step 1: Update views.py

Open the views.py file in your app and render your template using the render() function:

from django.shortcuts import render

def home(request):
    # You can pass data to the template
    context = {
        'site_name': 'My Awesome Site',
        'year': 2026
    }
    return render(request, 'pages/home.html', context)

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

Step 2: Update urls.py

In your app's urls.py, create URL paths for these views:

from django.urls import path
from . import views

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

Step 3: Run the server and view your pages

python manage.py runserver

Open your browser and navigate to:

4.5 Passing Data to Templates

You can pass data from your view to templates using a context dictionary:

def product_list(request):
    # Get data from database
    products = Product.objects.all()
    
    # Pass to template
    context = {
        'products': products,
        'total_products': products.count(),
        'title': 'Our Products'
    }
    return render(request, 'pages/products.html', context)
    

Then in your template, you can use this data:

<h1>{{ title }}</h1> <p>Total Products: {{ total_products }}</p> <ul> {% for product in products %} <li> <h3>{{ product.name }}</h3> <p>Price: ${{ product.price }}</p> </li> {% empty %} <p>No products found.</p> {% endfor %} </ul>

Summary: How Templates Work

Template Flow:
  1. base.html - The main layout with blocks (slots) for dynamic content
  2. components/ - Reusable HTML pieces included in the base template
  3. pages/*.html - Child templates that extend base.html and fill the blocks
  4. views.py - Renders the templates and passes data to them
  5. urls.py - Maps URLs to the views that render these templates

Complete Project Structure with Templates

myproject/ ├── manage.py ├── myproject/ │ ├── __init__.py │ ├── settings.py (Add your app to INSTALLED_APPS here) │ ├── urls.py (Include app URLs here) │ └── wsgi.py └── yourapp/ ├── __init__.py ├── admin.py (Register models here) ├── apps.py ├── models.py (Define database tables here) ├── urls.py (Define URL patterns with parameters here) ├── views.py (Write view functions and render templates here) └── templates/ ├── base.html (Main layout with blocks) ├── pages/ │ ├── home.html (Child template extending base) │ └── about.html └── components/ ├── header.html (Reusable components) └── footer.html

Quick Reference Commands

Command Purpose
py install 3.13 Install Python 3.13 using py launcher
python -m venv env Create virtual environment
env\Scripts\activate Activate virtual environment (Windows)
deactivate Deactivate virtual environment
pip install django Install Django
django-admin startproject project_name Create new Django project
python manage.py startapp app_name Create new Django app
python manage.py makemigrations Create migrations for model changes
python manage.py migrate Apply migrations to database
python manage.py createsuperuser Create admin user for the admin panel
python manage.py runserver Start development server

Pro Tips:
Complete Request-Response Flow:
  1. User visits → http://127.0.0.1:8000/product/5/
  2. URLs.py captures → the parameter '5' from the URL
  3. View function receives → the parameter and queries the database
  4. Model returns → the specific product with ID = 5
  5. View passes data → to a template through context dictionary
  6. Template renders → the HTML with dynamic data inserted
  7. User sees → a complete HTML page in their browser

This guide provides a complete foundation for Django development. Continue learning about forms, authentication, and REST APIs for full-stack development.

Happy Coding with Django! 🚀