What are Django Views?

Views are Python functions or classes that handle HTTP requests and return HTTP responses. They contain the business logic of your application and decide what data to display and how to display it.

Function-Based Views

Simple views using functions:

from django.http import HttpResponse
from django.shortcuts import render

def home(request):
    return HttpResponse("Hello, World!")

def about(request):
    return render(request, 'about.html', {'title': 'About Us'})

Class-Based Views

Views using classes (more reusable):

from django.views import View
from django.http import HttpResponse

class HomeView(View):
    def get(self, request):
        return HttpResponse("Hello, World!")
    
    def post(self, request):
        # Handle POST request
        return HttpResponse("POST received")

Request Object

The request object contains information about the HTTP request:

def my_view(request):
    # Request method
    method = request.method  # 'GET', 'POST', etc.
    
    # GET parameters
    name = request.GET.get('name', 'Guest')
    
    # POST data
    if request.method == 'POST':
        email = request.POST.get('email')
    
    # Headers
    user_agent = request.META.get('HTTP_USER_AGENT')
    
    # User information
    user = request.user
    
    return HttpResponse(f"Hello, {name}")

Rendering Templates

Return HTML using templates:

from django.shortcuts import render

def product_list(request):
    products = [
        {'name': 'Product 1', 'price': 10},
        {'name': 'Product 2', 'price': 20}
    ]
    
    context = {
        'products': products,
        'title': 'Products'
    }
    
    return render(request, 'products/list.html', context)

Working with Models

Query and display model data:

from django.shortcuts import render, get_object_or_404
from .models import Book

def book_list(request):
    books = Book.objects.all()
    return render(request, 'books/list.html', {'books': books})

def book_detail(request, book_id):
    book = get_object_or_404(Book, id=book_id)
    return render(request, 'books/detail.html', {'book': book})

Handling Forms

Process form submissions:

from django.shortcuts import render, redirect
from .forms import ContactForm

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('success')
    else:
        form = ContactForm()
    
    return render(request, 'contact.html', {'form': form})

Common View Patterns

List View

from django.views.generic import ListView
from .models import Article

class ArticleListView(ListView):
    model = Article
    template_name = 'articles/list.html'
    context_object_name = 'articles'
    paginate_by = 10

Detail View

from django.views.generic import DetailView
from .models import Article

class ArticleDetailView(DetailView):
    model = Article
    template_name = 'articles/detail.html'
    context_object_name = 'article'

Create View

from django.views.generic import CreateView
from django.urls import reverse_lazy
from .models import Article
from .forms import ArticleForm

class ArticleCreateView(CreateView):
    model = Article
    form_class = ArticleForm
    template_name = 'articles/create.html'
    success_url = reverse_lazy('article_list')

Response Types

Different types of responses:

from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.shortcuts import redirect

# Plain text
return HttpResponse("Hello")

# JSON
return JsonResponse({'status': 'success'})

# Redirect
return redirect('home')
return HttpResponseRedirect('/home/')

View Decorators

Add functionality with decorators:

from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods

@login_required
def profile(request):
    return render(request, 'profile.html')

@require_http_methods(["GET", "POST"])
def my_view(request):
    # Only allows GET and POST
    pass

Best Practices

  • Keep views thin: Move business logic to models or separate modules
  • Use class-based views: More reusable and maintainable
  • Handle errors: Use get_object_or_404 for missing objects
  • Use decorators: For authentication, permissions, etc.
  • Return appropriate responses: Use correct HTTP status codes

Next Steps

Learn about URL routing to connect URLs to views, or explore templates for rendering HTML.