Chapter 8: Django Views

URLs wired up, and the server running. Now we’re diving into Django Views — the heart of what makes your site dynamic.

Think of views as the brain workers of your Django app:

  • User visits a URL (e.g. /polls/)
  • Django’s URL dispatcher says: “Hey, this path matches → call this view!”
  • The view receives the request, does work (query DB, calculate something, check login…), and returns a response (HTML page, JSON, redirect, error, etc.)

Views are where the action happens — they’re Python callables (usually functions or classes) that take an HttpRequest and return an HttpResponse (or raise an exception like Http404).

In Django 6.0 (as of today), views work exactly like in 5.x for most cases — no massive breaking changes in views themselves. Async support is stronger (you can write async def views natively without wrappers), but we’ll start simple.

We’ll cover both styles step-by-step: Function-Based Views (FBVs) and Class-Based Views (CBVs) — with examples in your polls app.

1. Function-Based Views (FBVs) – The Simple & Beginner-Friendly Way

Most people (including the official tutorial) start here. It’s just a Python function.

Why FBVs first?

  • Super readable — easy to see what happens from top to bottom
  • No magic inheritance
  • Perfect for learning logic flow
  • Still used in 80%+ of real projects for custom/complex views

Example 1: Basic “Hello” View (what we already did)

In polls/views.py:

Python
  • request: The incoming HTTP request (contains GET/POST data, user info, headers…)
  • Return HttpResponse: Sends HTML/text back
  • URL mapping in polls/urls.py:
Python

→ Visit /polls/ → see the message.

Example 2: Dynamic with Database (Real Power!)

Assume you have the Question model from earlier.

Python
  • render() shortcut: Loads template + adds context + handles request
  • No manual HttpResponse(template.render(…)) — cleaner!

Create polls/templates/polls/index.html (namespaced folder!):

HTML

→ Refresh /polls/ → dynamic list from DB!

Example 3: Detail View with Error Handling

Python

In polls/urls.py:

Python
  • <int:question_id>: Captures number from URL (e.g. /polls/3/)
  • get_object_or_404(): Clean — no try/except mess

polls/templates/polls/detail.html:

HTML

→ /polls/1/ → shows question + choices (if exists)

Example 4: Handling POST (Voting – Simple Version)

Python

URL: path(‘<int:question_id>/vote/’, views.vote, name=’vote’),

  • request.POST: Form data
  • Always redirect after successful POST

2. Class-Based Views (CBVs) – When You Want Reusability

CBVs use classes + inheritance. Great for repeating patterns (list, detail, create…).

Why learn CBVs?

  • Less code for common tasks (with generics)
  • Mixins for custom behavior
  • But: steeper learning curve at first

Simple CBV Example (TemplateView – No DB)

Python

URL: path(‘about/’, AboutView.as_view(), name=’about’),

Template: polls/templates/polls/about.html

HTML

→ /polls/about/ → dynamic context!

Generic CBV Example (DetailView – Replaces our detail FBV)

Python

URL: path(‘<int:question_id>/’, QuestionDetailView.as_view(), name=’detail’),

  • Auto does get_object_or_404
  • Much less code!

FBV vs CBV – Quick 2026 Comparison Table

Aspect Function-Based Views (FBV) Class-Based Views (CBV)
Readability for beginners ★★★★★ Very clear flow ★★★☆☆ Need to know methods/parent classes
Custom logic Easy – just write code Override methods (get/post/get_context_data…)
Reusability Copy-paste or decorators Inheritance + mixins (very powerful)
Common tasks (CRUD) Manual Generic views (ListView, CreateView…) save tons
When to use in 2026 Custom logic, APIs, simple pages Admin-like interfaces, forms, lists/details
Async support async def works great async def get/post in custom classes

My advice today: Start with FBVs (like the poll tutorial) → they teach you what is happening. Later switch to CBVs for DRY code.

Quick Recap & Homework

  • View = request → logic → response
  • FBV: def my_view(request): return render(…)
  • CBV: class MyView(View): def get(self, request): …
  • Always use shortcuts: render, get_object_or_404, redirect, reverse

Next?

  • Want to add full voting + results views (FBV or CBV)?
  • “Show me ListView + CreateView for questions”
  • “How to make views login-required?”
  • Or “I tried this code → error!”

Paste any code/error — we’ll debug together. You’re crushing it, boss! 🚀 Let’s build more!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *