Function-Based Views
Learn how to create function-based views in Django to handle web requests and render templates. This is a foundational concept in Python web development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Python/Django experience. Take your time with each section and practice the examples
Understanding Django Views
Views are Python functions that take a web request and return a web response. They handle the logic of your web application and determine what data gets sent to the template.. This is an essential concept that every Python/Django developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Basic Function-Based Views
# views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from django.views.decorators.http import require_http_methods
from .models import Post, Category
def home(request):
"""Home page view"""
posts = Post.objects.filter(published_date__isnull=False).order_by('-published_date')[:5]
context = {
'posts': posts,
'title': 'Welcome to My Blog'
}
return render(request, 'blog/home.html', context)
def post_list(request):
"""List all published posts"""
posts = Post.objects.filter(published_date__isnull=False).order_by('-published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
"""Show a single post"""
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def category_posts(request, category_slug):
"""Show posts by category"""
category = get_object_or_404(Category, slug=category_slug)
posts = Post.objects.filter(category=category, published_date__isnull=False)
return render(request, 'blog/category_posts.html', {
'category': category,
'posts': posts
})
# HTTP method decorators
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET", "POST"])
def contact(request):
if request.method == 'POST':
# Handle form submission
name = request.POST.get('name')
email = request.POST.get('email')
message = request.POST.get('message')
# Process the form data
return HttpResponse('Thank you for your message!')
else:
# Show the contact form
return render(request, 'blog/contact.html')
# Custom HTTP responses
def api_data(request):
"""Return JSON data"""
from django.http import JsonResponse
data = {
'posts': list(Post.objects.values('title', 'created_date')[:10])
}
return JsonResponse(data)
def download_file(request, filename):
"""Serve a file for download"""
from django.http import FileResponse
import os
file_path = os.path.join('media', 'documents', filename)
if os.path.exists(file_path):
return FileResponse(open(file_path, 'rb'))
else:
raise Http404("File not found")