← Back to Chapters

Function-Based Views (FBVs)

? Function-Based Views (FBVs)

? Quick Overview

In Django, a view is a function that receives a web request and returns a web response. Function-based views (FBVs) are the most straightforward type of view, where a Python function is mapped to a URL pattern and is responsible for returning an HTTP response.

? Key Concepts

  • Views handle HTTP requests and responses
  • FBVs are plain Python functions
  • Easy to read, test, and debug

? Syntax / Theory

? View Code Example
# Import HttpResponse class
from django.http import HttpResponse
def my_view(request):
    # Return simple HTTP response
    return HttpResponse("Hello, World!")

? Adding FBV to URLs

? View Code Example
# URL configuration file
from django.urls import path
from . import views
urlpatterns = [
    # Map URL to view function
    path('hello/', views.my_view, name='hello'),
]

? Returning Different Responses

? View Code Example
# Render HTML template
from django.shortcuts import render
def home_view(request):
    return render(request, 'home.html', {'greeting': 'Hello, World!'})
? View Code Example
# Return JSON response
from django.http import JsonResponse
def api_view(request):
    data = {'message': 'Hello, World!'}
    return JsonResponse(data)

? Explanation

  • FBVs are simple Python functions
  • Mapped using path() in urls.py
  • Support multiple response types

? Interactive Example

Change the message inside HttpResponse() and refresh the browser to see instant updates.

Hello, Django!

? Use Cases

  • Simple pages
  • API endpoints
  • Form handling

? Tips & Best Practices

  • Keep views small and focused
  • Use render() for templates
  • Use JsonResponse for APIs

? Try It Yourself

  • Create a greeting FBV
  • Render template with context
  • Map URL and test in browser