Junior — Middle
How does Django generate and return HTTP responses to clients?
sobes.tech AI
Answer from AI
Django forms HTTP responses through the HttpResponse object. When a handler (view) receives a request, it performs the necessary logic, then creates an instance of HttpResponse or its subclasses, specifying the response content, status, and headers.
Example of a simple view:
from django.http import HttpResponse
def my_view(request):
content = "Hello, world!"
return HttpResponse(content, content_type="text/plain")
Django then sends this object back to the client, forming a correct HTTP response with the specified body and headers. You can also use classes like JsonResponse for JSON responses and other specialized classes.