In Django, views can return HTML responses or JSON data depending on the needs of your application. HTML responses are typically returned when you want to display a page to the user, while JSON responses are used when you're developing APIs or sending data in a machine-readable format.
Django views can return responses using HttpResponse, render(), or JsonResponse. The response type depends on whether you want to return markup or structured data.
# Returning static HTML directly
from django.http import HttpResponse
def my_view(request):
return HttpResponse("<h1>Welcome to My Website</h1><p>This is a simple HTML response.</p>")
This approach is useful for very simple responses or quick testing.
# Rendering a template with dynamic data
from django.shortcuts import render
def home_view(request):
context = {'message': 'Welcome to my homepage!'}
return render(request, 'home.html', context)
The render() function combines a template with context data to generate dynamic HTML.
# Returning JSON data for an API
from django.http import JsonResponse
def api_view(request):
data = {'message': 'Hello, World!', 'status': 'success'}
return JsonResponse(data)
Django automatically serializes Python dictionaries into JSON.
# Sending structured product data
from django.http import JsonResponse
def product_api(request):
product_data = {
'id': 1,
'name': 'Laptop',
'price': 999.99
}
return JsonResponse(product_data)
Browser renders full web page.
Client receives raw JSON like:
{"message":"Hello, World!","status":"success"}Simulate a Django View Response: Click a button to see how the client receives the data.
Waiting for request...
// Simulated frontend fetch call
fetch("/api/data/")
.then(response => response.json())
.then(data => console.log(data))
This simulates how frontend JavaScript consumes JSON APIs.
render() for templatesJsonResponse for APIs