A view is a callable that takes an HttpRequest and returns an HttpResponse. Views query models, enforce permissions, and choose templates or JSON.
Function-based view
from django.shortcuts import render
def index(request):
articles = Article.objects.filter(published=True)[:10]
return render(request, "blog/index.html", {"articles": articles})
HttpResponse shortcuts
render()— template + contextredirect()— 302 to another URLget_object_or_404()— fetch or 404JsonResponse— JSON APIs
Important interview questions and answers
- Q: What must every view return?
A: An HttpResponse subclass—render and JsonResponse wrap this for you. - Q: request.method values?
A: GET, POST, PUT, PATCH, DELETE, etc.—branch logic on method for forms. - Q: Fat views anti-pattern?
A: Views with too much business logic—extract to models/services for testability.
Self-check
- What arguments does
render()take? - When use
get_object_or_404instead of.get()?