In Django, views are the heart of your application. They control what data is shown and how itโs displayed. A view takes a request from the user and returns a response. In this article, weโll explore Function-Based Views (FBVs), how they work, and how to handle different request methods (GET, POST).
๐ What is a View?
A view is a Python function (or class) that receives a web request and returns a web response.
Simplest view (blog/views.py):
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django Views!")
Then connect it in blog/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
Visiting http://127.0.0.1:8000/ will now show: Hello, Django Views!
๐ฆ Rendering Templates in Views
Instead of plain text, we usually render HTML templates
def home(request):
return render(request, 'blog/home.html', {"message": "Welcome to the Blog"})
Now in blog/templates/blog/home.html
<h1>{{ message }}</h1>
This will display: Welcome to the Blog
๐ Handling GET and POST Requests
Views can handle multiple request methods:
def contact(request):
if request.method == "POST":
name = request.POST.get("name")
return HttpResponse(f"Thanks for contacting us, {name}!")
return HttpResponse("Contact Form Page")
If itโs a GET request, it shows the form page.
If itโs a POST request, it processes submitted data.
๐ Returning Different Response Types
- 1๏ธโฃ JSON Response
from django.http import JsonResponse
def api_data(request):
return JsonResponse({"status": "success", "data": [1, 2, 3]})
- 2๏ธโฃ Redirect
from django.shortcuts import redirect
def redirect_home(request):
return redirect('home')
โก Advantages of FBVs
Easy to understand and quick to write.
Perfect for simple views like forms, API endpoints, or basic pages.
Direct control over request/response handling.
โ ๏ธ When FBVs Become Complex
As logic grows, FBVs can become messy with many if/else conditions. Example:
def post_handler(request):
if request.method == "GET":
return HttpResponse("Show posts")
elif request.method == "POST":
return HttpResponse("Create post")
elif request.method == "PUT":
return HttpResponse("Update post")
else:
return HttpResponse("Unsupported method")
This works or we can create a separate functions and urls, but it gets harder to maintain. Thatโs why Django also provides Class-Based Views (CBVs) (coming in a later article).
๐ Summary
Views take a request and return a response.
FBVs are functions that handle logic directly.
You can return HTML, JSON, or redirects.
FBVs are great for simple use cases, but can get messy for complex ones.
Top comments (0)