← Back to Django, page 1

django-0007 · Easy fresher

What is a function-based view in Django, and when do you use render(), HttpResponse, JsonResponse and redirect()?

A function-based view is a Python function that takes an HttpRequest and returns an HttpResponse. HttpResponse sends raw content, render() fills a template and returns HTML, JsonResponse serialises a dict to JSON with the right content type, and redirect() returns a 302 to another URL or named route.

Full answer

A view is any callable that takes a request and returns a response. The simplest kind is a plain function:

python
def hello(request):
    return HttpResponse("Hello")

The request object carries everything about the call: request.method, request.GET (query string), request.POST (form data), request.headers, request.user (with auth middleware), request.COOKIES, request.FILES.

Ways to respond:

  • HttpResponse(content, status=200, content_type=...) for plain text or anything you build yourself.
  • render(request, "students/list.html", {"students": qs}) loads a template, fills it with context and returns an HttpResponse.
  • JsonResponse({"present": 28}) dumps the dict to JSON and sets Content-Type: application/json. To return a list, pass safe=False.
  • redirect("student-list") or redirect(obj) (calls obj.get_absolute_url()) returns a 302. Pass permanent=True for 301.
  • HttpResponseNotAllowed, HttpResponseBadRequest and friends for specific status codes, or raise Http404.

A common pattern for forms is "POST, then redirect, then GET" (Post/Redirect/Get). After a successful POST, redirect so a browser refresh does not submit the form again.

Decorators add behaviour: @require_POST, @require_http_methods(["GET", "POST"]), @login_required, @cache_page(60).

Function views are easy to read for small, one-off logic. Class-based views help when many views share the same shape.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import json
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.test import RequestFactory
from django.urls import path
from django.views.decorators.http import require_POST

def attendance_summary(request):
    present = int(request.GET.get("present", 0))
    return JsonResponse({"class": "10A", "present": present})

def roll_numbers(request):
    return JsonResponse([1, 2, 3], safe=False)

@require_POST
def mark_present(request):
    # ... save the attendance record here ...
    return redirect("summary")

urlpatterns = [path("summary/", attendance_summary, name="summary")]
settings.ROOT_URLCONF = __name__

rf = RequestFactory()
r1 = attendance_summary(rf.get("/summary/", {"present": "28"}))
print(r1.status_code, r1["Content-Type"], json.loads(r1.content))
print(roll_numbers(rf.get("/")).content.decode())

r2 = mark_present(rf.post("/mark/"))
print(r2.status_code, r2["Location"])
print(mark_present(rf.get("/mark/")).status_code)  # GET is not allowed

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 200 application/json {'class': '10A', 'present': 28} [1, 2, 3] 302 /summary/ 405

Key points

  • A view takes HttpRequest and returns HttpResponse
  • render() = template + context -> HttpResponse
  • JsonResponse needs safe=False for non-dict data
  • Redirect after a successful POST
  • Decorators like require_POST restrict methods

Common mistakes

  • Returning a dict from a view instead of a response object
  • Passing a list to JsonResponse without safe=False
  • Rendering a page directly after POST, which causes double submits on refresh
  • Reading request.POST for JSON bodies (use json.loads(request.body))

Follow-ups

  • How do you read a JSON request body in a plain Django view?
  • What does the Post/Redirect/Get pattern prevent?
  • When would you switch to a class-based view?

Tips

  • Mention request.GET vs request.POST vs request.body
  • Explain safe=False rather than just using it
  • Bring up Post/Redirect/Get for form handling