Django views
A Django view is a callable that takes a request and returns a response. Function views are def view(request):. Class-based views put HTTP methods on a class and are wired with .as_view().
Detailed Explanation
Django routes URLs to views in urls.py. A function view reads request.GET, request.POST, request.body, and the user on request.user, then returns HttpResponse, JsonResponse, or a redirect. Decorators (login_required, require_POST) wrap function views.
Class-based views (CBVs) implement get, post, and mixins (LoginRequiredMixin, ListView, DetailView). MyView.as_view() is the callable you put in urls.py. self.request is set per request. CBVs are useful when you want to share a dispatch pipeline; they are opaque when the mixin stack is deep. A short function view is clearer than a View subclass with one method.
Django REST Framework extends this with APIView and viewsets. The idea is the same: a callable, a request, a response. Middleware wraps every request before and after the view. Context processors are for templates, not for JSON APIs.
Views should be thin. Validate input, call a service or the ORM, return a response. Business rules in a 200-line view are untestable without the test client. The test client (Client(), RequestFactory) is how you unit-test views; RequestFactory does not run middleware, Client does.
Async views (async def) exist on ASGI Django. ORM calls are still sync unless you use the async ORM APIs. Do not block the ASGI loop with sync ORM in an async view; Django will warn.
csrf_exempt is a sharp tool. Browser session POSTs need CSRF. Bearer-token APIs typically use a different auth path and exempt CSRF because they are not cookie-session forms.
Code Examples
from django.http import JsonResponse, HttpRequest, HttpResponseNotFound
ORDERS = {"11": {"cents": 2500}}
def order_detail(request: HttpRequest, order_id: str):
order = ORDERS.get(order_id)
if order is None:
return HttpResponseNotFound()
return JsonResponse(order)from django.views import View
class HealthView(View):
def get(self, request):
return JsonResponse({"ok": True})
# urlpatterns = [path("health", HealthView.as_view())]Common Gotchas
Forgetting `as_view()`
you put the class in `urlpatterns` and Django cannot call it. Use `HealthView.as_view()`.
Sync ORM inside `async def`
it can block the event loop. Use `sync_to_async` or sync views.
CSRF on cookie-authenticated POST
a 403 that looks like auth is often a missing token.
`RequestFactory` skips middleware
a test can pass and production fail on CSRF or auth middleware.