MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Function-Based Views (FBV)0%
Study Materials
Django for Backend DevelopmentProgress 0%
1.1Installing Django & Environment Setup1.2Django Project Structure1.3Creating First Django App
5.1Function-Based Views (FBV)5.2Class-Based Views (CBV)5.3URL Dispatcher and Routing
HomeTutorialsDjango for Backend DevelopmentFunction-Based Views (FBV)
Class-Based Views (CBV)

Function-Based Views (FBV)

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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

1from django.shortcuts import render, redirect, get_object_or_404
2from django.http import HttpResponse, JsonResponse, Http404
3from .models import Article
4 
5def article_detail_view(request, slug):
6 # 1. Inspect HTTP method
7 if request.method != "GET":
8 return HttpResponse("Method Not Allowed", status=405)
9 
10 # 2. Database query with safe 404 handler
11 article = get_object_or_404(Article, slug=slug, status="published")
12 
13 # 3. Render template with context
14 return render(request, "articles/detail.html", {
15 "article": article,
16 "page_title": article.title,
17 })

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:

1from django.contrib.auth.decorators import login_required
2from django.views.decorators.http import require_http_methods, require_POST
3from django.views.decorators.csrf import csrf_protect
4 
5# Enforce login and restrict strictly to POST requests
6@login_required
7@require_POST
8def delete_article_view(request, article_id):
9 article = get_object_or_404(Article, id=article_id, author=request.user)
10 article.delete()
11 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

1def search_view(request):
2 # Query parameters: ?q=django&sort=newest
3 query = request.GET.get("q", "").strip()
4 sort_order = request.GET.get("sort", "newest")
5 
6 # POST body data:
7 payload = request.POST.get("comment_body")
8 
9 # Uploaded files:
10 uploaded_image = request.FILES.get("avatar")
11 
12 # Request headers and client IP:
13 user_agent = request.headers.get("User-Agent")
14 remote_ip = request.META.get("REMOTE_ADDR")

5. Returning JSON Responses

For AJAX endpoints or lightweight APIs:

1def api_stats_view(request):
2 data = {
3 "active_users": 1420,
4 "uptime_percent": 99.98,
5 "region": "us-east-1",
6 }
7 return JsonResponse(data)

Interactive Quiz• Knowledge Check

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

Previous LessonNext Lesson
Template InheritanceClass-Based Views (CBV)

Practice Quiz

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

Mentor-Led Practical Training

Master Django for Backend Development with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext