Introduction
Django views handle HTTP requests and return responses. URLs map routes to views.
Function-Based Views
from django.http import HttpResponse, JsonResponse
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})
Class-Based Views
from django.views.generic import ListView, DetailView, CreateView
from .models import Book
class BookListView(ListView):
model = Book
template_name = "books/list.html"
context_object_name = "books"
class BookDetailView(DetailView):
model = Book
template_name = "books/detail.html"
class BookCreateView(CreateView):
model = Book
fields = ["title", "author", "price"]
success_url = "/books/"
URL Configuration
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path("books/", views.book_list, name="book_list"),
path("books/<int:book_id>/", views.book_detail, name="book_detail"),
path("books/create/", views.BookCreateView.as_view(), name="book_create"),
]
Practice Problems
- Create CRUD views for a model
- Use class-based generic views
- Implement detail views with URL parameters
- Add template context data
- Handle form submission in views