Django HTTP Redirect out of view function

Is there a way to redirect to another page in Django if it is outside the view function.

I need to be able to redirect anywhere in my application, not just when I return an HTTP response to the client.

I tried the redirect shortcut:

from django.shortcuts import redirect redirect("/some/url") 

and

 redirect("http://someserver.com/some/url") 

but this does not cause any noticeable action.

I need something like header("Location: /some/url"); in PHP, which can be used anywhere inside the script.

thanks

+4
source share
1 answer

You can abuse process_exception middleware:

 # middleware.py from django import shortcuts class Redirect(Exception): def __init__(self, url): self.url = url def redirect(url): raise Redirect(url): class RedirectMiddleware: def process_exception(self, request, exception): if isinstance(exception, Redirect): return shortcuts.redirect(exception.url) 

Then you can:

 from middleware import redirect redirect('/some/url/') 
+5
source

All Articles