Django: Python Web Framework
Build robust web applications with Django framework, from basics to advanced features. Complete guide with practical examples and best practices.
What You'll Master
Django Fundamentals
MVC pattern, settings, and project structure
Models and Database
ORM, migrations, and database relationships
Views and Templates
Function-based and class-based views, template system
Django REST Framework
Building APIs with serializers and viewsets
Authentication & Security
User management, permissions, and security features
Deployment & Production
WSGI, static files, and production deployment
Introduction to Django
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, 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.
Getting Started with Django
Django follows the MVT (Model-View-Template) pattern, which is similar to MVC but with Django's own twist. It provides a robust foundation for building web applications with built-in features for authentication, admin interface, and database management.
Installation and Project Setup
# Install Django
pip install django
# Create a new project
django-admin startproject myproject
cd myproject
# Create an app
python manage.py startapp myapp
# Run the development server
python manage.py runserverDjango Models
Models are the single, definitive source of information about your data. They contain the essential fields and behaviors of the data you're storing. Django uses an ORM (Object-Relational Mapping) to interact with the database.
Defining Models
from django.db import models
from django.contrib.auth.models import User
class Post(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)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Meta:
ordering = ['-created_at']Django Views
Views are Python functions that take a web request and return a web response. Django supports both function-based views and class-based views, giving you flexibility in how you structure your application logic.
Function-Based Views
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, 'posts/list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'posts/detail.html', {'post': post})
def api_posts(request):
posts = Post.objects.all()
data = [{'title': post.title, 'content': post.content} for post in posts]
return JsonResponse(data, safe=False)Django REST Framework
Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs. It provides serializers, viewsets, and authentication mechanisms that make it easy to build robust APIs.
API Serializers and Viewsets
from rest_framework import serializers, viewsets
from rest_framework.permissions import IsAuthenticated
from .models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'title', 'content', 'author', 'created_at']
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
permission_classes = [IsAuthenticated]
def perform_create(self, serializer):
serializer.save(author=self.request.user)Authentication and Security
Django provides a comprehensive authentication system out of the box. It includes user management, permissions, groups, and password hashing. You can also integrate with third-party authentication providers.
User Authentication
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard')
return render(request, 'auth/login.html')
@login_required
def dashboard(request):
return render(request, 'dashboard.html')Django Admin Interface
Django's admin interface is automatically generated based on your models. It provides a ready-to-use interface for managing your application's data and can be customized extensively.
Admin Configuration
from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'created_at']
list_filter = ['created_at', 'author']
search_fields = ['title', 'content']
readonly_fields = ['created_at', 'updated_at']
def get_queryset(self, request):
return super().get_queryset(request).select_related('author')Testing in Django
Django includes a comprehensive test framework that makes it easy to write unit tests, integration tests, and functional tests for your application.
Writing Tests
from django.test import TestCase, Client
from django.contrib.auth.models import User
from .models import Post
class PostModelTest(TestCase):
def setUp(self):
self.user = User.objects.create_user(
username='testuser',
password='testpass123'
)
def test_post_creation(self):
post = Post.objects.create(
title='Test Post',
content='Test content',
author=self.user
)
self.assertEqual(str(post), 'Test Post')
self.assertEqual(post.author, self.user)
class PostViewTest(TestCase):
def setUp(self):
self.client = Client()
self.user = User.objects.create_user(
username='testuser',
password='testpass123'
)
def test_post_list_view(self):
response = self.client.get('/posts/')
self.assertEqual(response.status_code, 200)Deployment and Production
Deploying Django applications to production requires careful configuration of static files, database settings, and security measures. Use WSGI servers like Gunicorn and reverse proxies like Nginx for optimal performance.
Best Practices
- Project Structure: Organize your code with proper app separation
- Settings Management: Use environment-specific settings files
- Database Optimization: Use select_related and prefetch_related for queries
- Security: Keep Django updated and follow security guidelines
- Testing: Write comprehensive tests for all functionality
Conclusion
Django is a powerful framework that provides everything needed to build robust web applications. Its "batteries included" philosophy means you have access to authentication, admin interface, ORM, and many other features out of the box. With Django REST Framework, you can easily build APIs that power modern web and mobile applications.