Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django HTTP Redirect outside of view function

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

like image 670
Michael Bates Avatar asked Dec 03 '12 04:12

Michael Bates


1 Answers

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.

like image 190
Jesse the Game Avatar answered Oct 22 '22 06:10

Jesse the Game