View (Django)
A Django view is the Python code that receives an HTTP request and returns an HTTP response. It can be a function (function-based view) or a class (class-based view), and it usually queries models and renders a template.
Django
Views hold your request-handling logic. A function-based view takes a request object as its first argument plus any captured URL parameters, does its work (querying models, processing forms), and returns an HttpResponse — often via the render() shortcut that renders a template to a response.
Remember Django's vocabulary: this 'view' is the controller in classic MVC. It should contain logic, not presentation; HTML belongs in templates and data rules belong in models.
For common patterns (listing objects, showing one object, handling a form), Django offers class-based generic views that remove boilerplate, but every view ultimately returns an HttpResponse, whether built by hand, by render(), by redirect(), or by a generic view.
Syntax
def my_view(request):
return render(request, "page.html", context)Examples
Python
from django.shortcuts import render, get_object_or_404
from .models import Post
def detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, "post.html", {"post": post})