← Back to Chapters

Working with Request & Response Objects

? Working with Request & Response Objects

? Quick Overview

In Django, middleware allows you to process request and response objects globally before they reach the view or after the view has processed the response. These objects are the backbone of how Django handles incoming data and sends responses back to the client.

? Key Concepts

  • Request Object – Represents the incoming HTTP request.
  • Response Object – Represents the outgoing HTTP response.
  • Middleware – Hooks that allow global request/response processing.

? Syntax & Theory

The request object provides access to HTTP methods, headers, user data, cookies, and payload. The response object allows modification of headers, status codes, cookies, and content before sending data back to the client.

? Code Example: Accessing Request Data

? View Code Example
# Middleware to log request information
class RequestLoggingMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
method = request.method
user = request.user
headers = request.headers
print(f"Request Method: {method}")
print(f"User: {user}")
print(f"Headers: {headers}")
response = self.get_response(request)
return response

? Code Example: Modifying Response

? View Code Example
# Middleware to add a custom response header
class CustomHeaderMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
response = self.get_response(request)
response['X-Custom-Header'] = 'This is a custom header'
return response

? Code Example: Modifying Request

? View Code Example
# Middleware to inject custom data into request
class AddContextToRequestMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
request.custom_data = 'This is some custom data'
response = self.get_response(request)
return response

? Live Output / Explanation

The middleware executes for every request. Request data can be logged or modified before reaching views, and response headers or content can be altered before returning to the client.

? Interactive Flow (Concept)

Client ➜ Middleware (Request) ➜ View ➜ Middleware (Response) ➜ Client

? Middleware Simulator

Configure middleware and click "Send Request" to watch the execution order.

Ready... Click 'Send Request' to start simulation.

? Use Cases

  • Request logging and analytics
  • Authentication & authorization checks
  • Injecting global context data
  • Adding security or tracking headers

✅ Tips & Best Practices

  • Keep middleware focused on a single responsibility.
  • Always call get_response(request).
  • Avoid heavy processing inside middleware.

? Try It Yourself

  • Create middleware to log IP address and user agent.
  • Add timing headers to measure response duration.
  • Attach custom request attributes and use them in views.