🎸 Django Beginner

What is Django middleware?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Django basics — a prerequisite for any developer role.

Answer

Django middleware is a framework of hooks into Django's request/response processing. Each middleware component processes requests before they reach the view and responses before they leave Django. Middleware is applied in the order defined in MIDDLEWARE (request phase: top-to-bottom; response phase: bottom-to-top). Built-in middleware: SecurityMiddleware — HTTPS redirect, security headers; SessionMiddleware — session support; CommonMiddleware — URL normalization, APPEND_SLASH; CsrfViewMiddleware — CSRF protection; AuthenticationMiddleware — attaches user to request; MessageMiddleware — flash messages; XFrameOptionsMiddleware — clickjacking protection. Custom middleware: class RequestLoggingMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): import time start = time.time() response = self.get_response(request) duration = time.time() - start logger.info(f"{request.method} {request.path} {response.status_code} {duration:.3f}s") return response def process_exception(self, request, exception): logger.error(f"Exception in {request.path}: {exception}") # return None to let default handler proceed. Hooks: __call__ — processes request AND response; process_view(request, view_func, view_args, view_kwargs) — before the view; process_exception(request, exception) — when view raises exception; process_template_response(request, response) — when response has a context. Register in settings: MIDDLEWARE = ["myapp.middleware.RequestLoggingMiddleware", ...].

Common Mistake

Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong Django candidates.