[docs]classHtmxMessageMiddleware(MiddlewareMixin):""" Middleware that handles Django messages in HTMX responses. Middleware that moves messages into the HX-Trigger header when request is made with HTMX. """
[docs]defprocess_response(self,request:HttpRequest,response:HttpResponse)->HttpResponse:""" Process HTMX responses by injecting Django messages as toast notifications. Args: request: The HTTP request response: The HTTP response Returns: The modified response with injected messages """# The HX-Request header indicates that the request was made with HTMXif"HX-Request"notinrequest.headers:returnresponse# Ignore HTTP redirections because HTMX cannot read the bodyif300<=response.status_code<400:returnresponse# Ignore client-side redirection because HTMX drops OOB swapsif"HX-Redirect"inresponse.headers:returnresponse# Extract the messagesmessages=get_messages(request)ifnotmessages:returnresponseresponse.write(render_to_string(template_name="toasts.html",context={"messages":messages},request=request,))returnresponse