The HttpResponse object sends data back to the user's web browser. It lets your Django app show text, HTML, or files as a response to a web request.
0
0
HttpResponse object in Django
Introduction
When you want to send simple text or HTML back to the user.
When you need to return a file like an image or PDF to the browser.
When you want to control the HTTP status code or headers in the response.
When building a custom view that does not use Django templates.
When you want to quickly test output from a view without templates.
Syntax
Django
HttpResponse(content='', status=200, content_type='text/html')
content is the text or bytes you want to send back.
status sets the HTTP status code (like 200 for OK).
Examples
Sends a simple text response 'Hello, world!' with default status 200 and content type 'text/html'.
Django
from django.http import HttpResponse def my_view(request): return HttpResponse('Hello, world!')
Sends JSON data with the correct content type so the browser knows it's JSON.
Django
from django.http import HttpResponse def json_view(request): data = '{"name": "Alice"}' return HttpResponse(data, content_type='application/json')
Sends a 404 status code with a simple message.
Django
from django.http import HttpResponse def not_found_view(request): return HttpResponse('Page not found', status=404)
Sample Program
This view sends a simple HTML heading as the response. The browser will display "Welcome to Django!" as a big heading.
Django
from django.http import HttpResponse def greeting_view(request): message = '<h1>Welcome to Django!</h1>' return HttpResponse(message, content_type='text/html')
OutputSuccess
Important Notes
The HttpResponse object can send any text or bytes, so you can use it for HTML, JSON, XML, or files.
Always set the content_type correctly so browsers handle the response properly.
For complex pages, Django templates are better, but HttpResponse is great for quick or custom responses.
Summary
The HttpResponse object sends data back to the browser.
You can set the content, status code, and content type.
It is useful for simple or custom responses without templates.