Skip to main content
Course/Module 4/Topic 1 of 5Intermediate

Function-Based Views

Learn how to create function-based views in Django to handle web requests and render templates.

60 minBy Priygop TeamLast updated: Feb 2026

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.

Basic Function-Based Views

Example
# 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")

📚 Additional Resources

Recommended Reading

  • Django Views Documentation
  • Django Templates Documentation
  • Django CBV by Classy Class-Based Views

Online Resources

  • Django Template Language
  • Django Generic Views
  • Template Tags and Filters
Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep