Django Web Framework

Learn how to build powerful web applications quickly with Django's "batteries-included" approach

Get Started

Why Django?

🚀

Rapid Development

Django's "batteries-included" philosophy means you can build applications quickly without reinventing the wheel.

🔒

Security

Django includes robust security features by default, helping protect against common vulnerabilities.

📈

Scalability

Used by Instagram, Pinterest, and Dropbox, Django can scale to handle millions of users.

Django Overview

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the Model-View-Template (MVT) architectural pattern, which is similar to MVC (Model-View-Controller) but with Django-specific terminology.

URL Dispatcher
View
Model
Template

When a request comes to a Django application:

  1. The URL dispatcher determines which view should handle the request
  2. The view interacts with the model to retrieve or update data
  3. The model handles data validation and database operations
  4. The view passes data to a template for rendering
  5. The rendered HTML is returned to the user

Getting Started with Django

Prerequisites

Before you start, make sure you have:

Installation

The recommended way to install Django is using pip, the Python package manager:

# Create a virtual environment python -m venv venv # Activate the virtual environment # On Windows: venv\Scripts\activate # On macOS/Linux: source venv/bin/activate # Install Django pip install django
Tip: Always use a virtual environment for your Django projects. This isolates dependencies for each project, preventing conflicts between different projects.

Creating Your First Django Project

Let's create a simple blog application to learn the basics:

# Create a new Django project django-admin startproject myblog # Navigate to the project directory cd myblog # Start the development server python manage.py runserver

You should now be able to visit http://127.0.0.1:8000/ in your browser and see Django's welcome page.

Project Structure

Your new Django project will have the following structure:

myblog/ # Root project directory manage.py # Command-line utility for administrative tasks myblog/ # Project package __init__.py # Empty file that tells Python this is a package settings.py # Project settings/configuration urls.py # URL declarations for the project asgi.py # ASGI configuration for deployment wsgi.py # WSGI configuration for deployment

Creating an App

Django projects are divided into "apps" - modular components that represent different parts of your application:

# Create a blog app python manage.py startapp blog

After creating the app, you need to register it in your project's settings. Open myblog/settings.py and add 'blog' to the INSTALLED_APPS list:

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', # Add your new app here ]

Models and Database

What are Models?

Models are Python classes that define the structure of your database tables. Each model typically corresponds to a single database table.

Creating Models

Let's create models for our blog application. Open blog/models.py and add:

from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return self.name class Meta: verbose_name_plural = "Categories" class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.title

Common Field Types

Migrations

After defining your models, you need to create and apply migrations to update your database schema:

# Create migrations python manage.py makemigrations # Apply migrations python manage.py migrate
Tip: Run migrations every time you change your models to keep your database schema in sync with your code.

Django Admin

Django comes with a powerful admin interface that allows you to manage your data. To use it, first create a superuser:

python manage.py createsuperuser

Then, register your models in blog/admin.py:

from django.contrib import admin from .models import Category, Post admin.site.register(Category) admin.site.register(Post)

Now you can access the admin interface at http://127.0.0.1:8000/admin/ and manage your blog posts and categories.

Views and URL Patterns

What are Views?

Views are Python functions or classes that receive a web request and return a web response. Views access data through models and pass it to templates for rendering.

Creating Function-Based Views

Let's create views for our blog app. Open blog/views.py and add:

from django.shortcuts import render, get_object_or_404 from .models import Post, Category def home(request): posts = Post.objects.all().order_by('-date_posted') context = { 'posts': posts, 'title': 'Home' } return render(request, 'blog/home.html', context) def post_detail(request, post_id): post = get_object_or_404(Post, id=post_id) context = { 'post': post, 'title': post.title } return render(request, 'blog/post_detail.html', context) def category_posts(request, category_id): category = get_object_or_404(Category, id=category_id) posts = Post.objects.filter(category=category).order_by('-date_posted') context = { 'category': category, 'posts': posts, 'title': f'Category: {category.name}' } return render(request, 'blog/category_posts.html', context)

URL Patterns

URL patterns map URLs to views. First, create a blog/urls.py file:

from django.urls import path from . import views urlpatterns = [ path('', views.home, name='blog-home'), path('post//', views.post_detail, name='post-detail'), path('category//', views.category_posts, name='category-posts'), ]

Then, update the project's main URL configuration in myblog/urls.py:

from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ]

Class-Based Views

Django also supports class-based views, which can help organize code and provide reusable functionality:

from django.views.generic import ListView, DetailView from .models import Post class PostListView(ListView): model = Post template_name = 'blog/home.html' # /_.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html'

To use class-based views, update your URL patterns:

from django.urls import path from . import views from .views import PostListView, PostDetailView urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post//', PostDetailView.as_view(), name='post-detail'), path('category//', views.category_posts, name='category-posts'), ]

Templates

Template Basics

Templates are HTML files with Django Template Language (DTL) that allow you to dynamically generate HTML. Create the following directory structure for templates:

blog/ templates/ blog/ base.html home.html post_detail.html category_posts.html

Base Template

Create a base template that other templates will extend (blog/templates/blog/base.html):

{% block title %}My Blog{% endblock %}
{% block content %}{% endblock %}

© 2025 My Blog

Home Template

Create a template for the home page (blog/templates/blog/home.html):

{% extends 'blog/base.html' %} {% block title %} {{ title }} - My Blog {% endblock %} {% block content %}

Latest Posts

{% for post in posts %}

{{ post.title }}

{{ post.date_posted|date:"F d, Y" }} by {{ post.author.username }} {% if post.category %} in {{ post.category.name }} {% endif %}

{{ post.content|truncatewords:50 }}

Read More
{% empty %}

No posts available.

{% endfor %} {% if is_paginated %}
    {% if page_obj.has_previous %}
  • First
  • Previous
  • {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %}
  • {{ num }}
  • {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
  • {{ num }}
  • {% endif %} {% endfor %} {% if page_obj.has_next %}
  • Next
  • Last
  • {% endif %}
{% endif %} {% endblock %}

Template Tags and Filters

Django Template Language includes various tags and filters:

Common tags and filters:

Forms and User Input

Django Forms

Django forms help you handle user input, validation, and security. Create a blog/forms.py file:

from django import forms from .models import Post, Category class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content', 'category'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}), 'category': forms.Select(attrs={'class': 'form-control'}), }

Creating a New Post View

Add a view to handle form submission:

from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import PostForm @login_required def create_post(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post-detail', post_id=post.id) else: form = PostForm() return render(request, 'blog/create_post.html', {'form': form, 'title': 'Create Post'})

Update blog/urls.py to include the new view:

path('post/new/', views.create_post, name='create-post'),

Create Post Template

Create blog/templates/blog/create_post.html:

{% extends 'blog/base.html' %} {% block title %} {{ title }} - My Blog {% endblock %} {% block content %}

Create New Post

{% csrf_token %}
{{ form.title }}
{{ form.category }}
{{ form.content }}
{% endblock %}
Security Note: Always include the {% raw %}{% csrf_token %}{% endraw %} tag in your forms to protect against Cross-Site Request Forgery attacks.

Form Validation

Django automatically validates form input based on model fields. You can add custom validation by overriding the clean method:

from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content', 'category'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}), 'category': forms.Select(attrs={'class': 'form-control'}), } def clean_title(self): title = self.cleaned_data.get('title') if len(title) < 5: raise forms.ValidationError("Title must be at least 5 characters long.") return title

User Authentication

User Registration

Django's authentication system makes it easy to handle user accounts. Create a new app for user management:

python manage.py startapp users

Add 'users' to INSTALLED_APPS in settings.py.

Create a registration form in users/forms.py:

from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2']

Create views in users/views.py:

from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}! You can now log in.') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form})

Add URL patterns in myblog/urls.py:

from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('blog.urls')), ]

Create templates for user authentication in users/templates/users/.

Tip: Django's built-in authentication views handle login, logout, password reset, and more. You just need to provide templates.

Additional Resources

Official Django Documentation

Comprehensive and well-organized documentation for Django.

Visit

Django for Beginners

An excellent book for beginners by William S. Vincent.

Visit

MDN Django Tutorial

Mozilla's tutorial on building a library catalog with Django.

Visit
Reading Progress