Module 4: Views & Templates

Learn Django views, templates, context data, template inheritance, and URL patterns for web development.

Back to Course|4.5 hours|Intermediate

Views & Templates

Learn Django views, templates, context data, template inheritance, and URL patterns for web development.

Progress: 0/5 topics completed0%

Select Topics Overview

Function-Based Views

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

Content by: Manali Trivedi

Python Django Developer

Connect

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

Code 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")
Swipe to see more code

🎯 Practice Exercise

Test your understanding of this topic:

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

Ready for the Next Module?

Continue your learning journey and master the next set of concepts.

Continue to Module 5