Is there a way to redirect to another page in Django when outside of a view function.
I need to be able to redirect anywhere in my app, NOT just when I'm returning an HTTP response back to the client.
I've tried the redirect shortcut:
from django.shortcuts import redirect
redirect("/some/url")
and also
redirect("http://someserver.com/some/url")
but this does no noticable action.
I need something like header("Location: /some/url");
in PHP which can be used anywhere inside the script.
Thanks
You could abuse/leverage process_exception
of 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)
You can then do:
from middleware import redirect
redirect('/some/url/')
Also don't forget to add RedirectMiddleware
to your MIDDLEWARE_CLASSES
settings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With