← Back to Python

All Topics

Advertisement

Learn/Python/Web Development

Django Views and URLs

Topic: Django

Advertisement

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

  1. Create CRUD views for a model
  2. Use class-based generic views
  3. Implement detail views with URL parameters
  4. Add template context data
  5. Handle form submission in views

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →