Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers at the Lawrence Journal-World newspaper, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel.
Django was created in 2003 by Adrian Holovaty and Simon Willison while working at the Lawrence Journal-World newspaper in Kansas. They needed to build web applications quickly to meet tight newsroom deadlines, leading to the creation of a framework that prioritizes rapid development and clean code.
The framework was named after Django Reinhardt, a jazz guitarist known for his innovative style and technical prowess – qualities that the framework embodies in web development.
Django follows the "batteries included" philosophy, providing a comprehensive set of tools and features out of the box:
Django's design enables developers to build applications quickly:
# Create a blog post model in minutes
class BlogPost(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
# Automatic admin interface
@admin.register(BlogPost)
class BlogPostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'created_at']
Django includes built-in protection against common web vulnerabilities:
# CSRF protection is automatic in forms
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Django scales from small projects to high-traffic applications:
Django works for various types of applications:
Django uses the MVT pattern, a variation of MVC:
# Model (Data Layer)
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()
# View (Logic Layer)
def product_list(request):
products = Product.objects.all()
return render(request, 'products/list.html', {'products': products})
# Template (Presentation Layer)
# products/list.html
{% for product in products %}
<div class="product">
<h3>{{ product.name }}</h3>
<p>${{ product.price }}</p>
<p>{{ product.description }}</p>
</div>
{% endfor %}
Write database queries using Python instead of SQL:
# Instead of SQL: SELECT * FROM products WHERE price > 100
expensive_products = Product.objects.filter(price__gt=100)
# Complex queries with relationships
recent_posts = BlogPost.objects.select_related('author').filter(
created_at__gte=timezone.now() - timedelta(days=7)
).order_by('-created_at')
Automatic administrative interface for your models:
# Minimal admin configuration
admin.site.register(Product)
# Advanced admin customization
@admin.register(BlogPost)
class BlogPostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'status', 'created_at']
list_filter = ['status', 'created_at', 'author']
search_fields = ['title', 'content']
prepopulated_fields = {'slug': ('title',)}
date_hierarchy = 'created_at'
Clean, flexible URL patterns:
from django.urls import path, include
urlpatterns = [
path('', views.home, name='home'),
path('products/', views.product_list, name='product_list'),
path('products/<int:pk>/', views.product_detail, name='product_detail'),
path('api/', include('api.urls')),
]
Powerful template engine with inheritance:
<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<nav>{% include 'navigation.html' %}</nav>
<main>{% block content %}{% endblock %}</main>
</body>
</html>
<!-- product_list.html -->
{% extends 'base.html' %}
{% block title %}Products - {{ block.super }}{% endblock %}
{% block content %}
{% for product in products %}
<div class="product-card">
<h3>{{ product.name }}</h3>
<p>${{ product.price|floatformat:2 }}</p>
</div>
{% endfor %}
{% endblock %}
Instagram: Handles billions of photos and users
Pinterest: Visual discovery platform
Mozilla: Firefox browser and web services
The Washington Post: News and media platform
Spotify: Music streaming service
E-commerce: Shopify alternatives, marketplace platforms Media & Publishing: News sites, blogs, content platforms Social Networks: Community platforms, forums Financial Services: Banking applications, fintech startups Healthcare: Patient management systems, telemedicine platforms Education: Learning management systems, online courses
# Django REST Framework - API development
INSTALLED_APPS = [
'rest_framework',
'corsheaders',
]
# Celery - Asynchronous task processing
from celery import shared_task
@shared_task
def send_email_notification(user_id):
# Background email sending
pass
# Django Channels - WebSocket support
INSTALLED_APPS = [
'channels',
]
# Real-time chat functionality
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
Django provides multiple optimization strategies:
# Efficient queries with select_related and prefetch_related
posts = BlogPost.objects.select_related('author').prefetch_related('tags')
# Database indexing
class BlogPost(models.Model):
title = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(unique=True) # Automatically indexed
# View-level caching
from django.views.decorators.cache import cache_page
@cache_page(60 * 15) # Cache for 15 minutes
def product_list(request):
return render(request, 'products/list.html')
# Template fragment caching
{% load cache %}
{% cache 500 product_list %}
<!-- Expensive template rendering -->
{% endcache %}
Django's learning curve is gentle, with excellent documentation:
pip install djangodjango-admin startproject mysitepython manage.py startapp myapppython manage.py runserverDjango's combination of rapid development, security, and scalability makes it an excellent choice for web applications ranging from simple blogs to complex enterprise systems. Its "batteries included" approach means you can focus on building your application's unique features rather than reinventing common web development patterns.
Introduction and Foundations
Welcome to the comprehensive Django guide. This section establishes the foundational knowledge required for effective Django development, covering everything from core concepts to your first working application.
Key Concepts and Philosophy
Django's design philosophy shapes every aspect of the framework, creating a consistent and predictable development experience. Understanding these principles will help you write better Django code and make architectural decisions that align with the framework's strengths.