Function-Based Views (FBV)0%

Function-Based Views (FBV)

Beginner12 min read•Updated: Jul 11, 2026
Study MaterialsCheatsheet

Function-Based Views (FBV)

In Django, Function-Based Views (FBVs) are Python functions that receive an HttpRequest object and return an HttpResponse. Because they are standard Python functions, FBVs are explicit, straightforward to read, and ideal for custom business workflows, multi-step wizards, or endpoints where class-based inheritance obscures control flow.


1. Anatomy of a Function-Based View

Python
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, JsonResponse, Http404
from .models import Article
 
def article_detail_view(request, slug):
# 1. Inspect HTTP method
if request.method != "GET":
return HttpResponse("Method Not Allowed", status=405)
 
# 2. Database query with safe 404 handler
article = get_object_or_404(Article, slug=slug, status="published")
 
# 3. Render template with context
return render(request, "articles/detail.html", {
"article": article,
"page_title": article.title,
})

2. Defensive Programming with get_object_or_404

A common beginner anti-pattern is using Article.objects.get() directly in views:

Visual Architecture & Process Flow

How data and code flow step-by-step

Flowchart
Step 1
# ❌ Dangerous: Throws unhandled Article.DoesNotExist exception
Step 2
500 Server Error!

3. Essential View Decorators

Django provides decorators to enforce protocols, authentication, and HTTP methods declaratively:

Python
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods, require_POST
from django.views.decorators.csrf import csrf_protect
 
# Enforce login and restrict strictly to POST requests
@login_required
@require_POST
def delete_article_view(request, article_id):
article = get_object_or_404(Article, id=article_id, author=request.user)
article.delete()
return redirect("articles:home")
  • @login_required: Redirects anonymous users to the login page (settings.LOGIN_URL).
  • @require_POST: Automatically returns 405 Method Not Allowed if accessed via GET.
  • @require_http_methods(["GET", "POST"]): Whitelists permitted HTTP verbs.

4. Reading Query Parameters and Request Payloads

Python
def search_view(request):
# Query parameters: ?q=django&sort=newest
query = request.GET.get("q", "").strip()
sort_order = request.GET.get("sort", "newest")
 
# POST body data:
payload = request.POST.get("comment_body")
 
# Uploaded files:
uploaded_image = request.FILES.get("avatar")
 
# Request headers and client IP:
user_agent = request.headers.get("User-Agent")
remote_ip = request.META.get("REMOTE_ADDR")

5. Returning JSON Responses

For AJAX endpoints or lightweight APIs:

Python
def api_stats_view(request):
data = {
"active_users": 1420,
"uptime_percent": 99.98,
"region": "us-east-1",
}
return JsonResponse(data)

Interactive Quiz

Practice Quiz

Question 1
Why is get_object_or_404 preferred over Model.objects.get() in Django views?
Question 2
How do you safely read an optional query parameter like ?page=2 in a view without throwing a KeyError?
Question 3
What HTTP status code does the @require_POST decorator return if a client sends a GET request?
Question 4
Where does the @login_required decorator redirect unauthenticated visitors by default?
Question 5
When are Function-Based Views (FBVs) typically preferred over Class-Based Views (CBVs)?
Next Lesson

Class-Based Views (CBV)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext