Function-Based Views (FBVs)
Function-Based Views (FBVs) are the simplest way to handle requests in Django. They are plain Python functions that take an HttpRequest and return an HttpResponse. FBVs are explicit, easy to understand, and great for simple logic.
20 min•By Priygop Team•Updated 2026
FBV Basics
- A view function receives HttpRequest, returns HttpResponse
- render(request, template, context) — Render HTML template
- redirect(url_or_name) — Redirect to another URL
- JsonResponse(data) — Return JSON data
- HttpResponse(content, status) — Return raw content
- get_object_or_404(Model, pk=id) — Get object or return 404
- Use request.method to check GET vs POST
FBV Examples
FBV Examples
# blog/views.py
# from django.shortcuts import render, redirect, get_object_or_404
# from django.http import HttpResponse, JsonResponse
# from .models import Post
# Simple view
# def home(request):
# return render(request, 'blog/home.html')
# View with database query
# def post_list(request):
# posts = Post.objects.all().order_by('-created_at')
# return render(request, 'blog/list.html', {'posts': posts})
# View with URL parameter
# def post_detail(request, pk):
# post = get_object_or_404(Post, pk=pk)
# return render(request, 'blog/detail.html', {'post': post})
# Handling GET and POST
# def create_post(request):
# if request.method == 'POST':
# title = request.POST.get('title')
# content = request.POST.get('content')
# Post.objects.create(title=title, content=content)
# return redirect('post-list')
# return render(request, 'blog/create.html')
# JSON response (for APIs)
# def api_posts(request):
# posts = list(Post.objects.values('id', 'title'))
# return JsonResponse({'posts': posts})Tip
Tip
Use blank=True for form validation and null=True for database NULLs. For strings, use blank=True without null=True (use empty string).
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Using null=True on CharField/TextField. Django stores empty strings, not NULL, for text fields. Use blank=True, default='' instead.
Practice Task
Note
(1) Add validators to a field. (2) Create a model with choices. (3) Add help_text for admin clarity.
Quick Quiz
Key Takeaways
- Function-Based Views (FBVs) are the simplest way to handle requests in Django.
- A view function receives HttpRequest, returns HttpResponse
- render(request, template, context) — Render HTML template
- redirect(url_or_name) — Redirect to another URL