[Answered ]-Is it possible to render a template from middleware?

2👍

You can catch those exceptions and return a HttpResponse object to render your custom template. Or maybe a redirect is also appropriate.

0👍

Yes… and no.

You can render whatever you want (your web server has a nice explanation how to do that), but whether the user will see that is his choice – through his browser settings. It is possible you render something, but the browser still shows a standard error page.

👤TomTom

0👍

A middleware might be a solution:

class MyExceptionMiddleware:
   def process_exception(self, request, exception):

     if isinstance(exception, CustomException):
       template = loader.get_template('Other500.html')
       context = RequestContext(request, {'message': 'Custom Message'})
       return HttpResponseForbidden(template.render(context))

     return None

Don’t forget to register the middleware in settings.py:

MIDDLEWARE_CLASSES = (
    ....
    'app.middleware.MyExceptionMiddleware',
👤maersu

Leave a comment