View Redirect Decorators

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from functools import wraps
from django.http import HttpResponsePermanentRedirect, HttpResponseRedirect

def permanent_redirect(url):
    """
    Executes a HTTP 301 (permanent) redirect after the view finishes processing. If a
    value is returned, it is ignored. Allows for the view url to be callable so the
    reverse() lookup can be used.

    @permanent_redirect('/another-url/')
    def redirect_view(request):
        ...

    @redirect(lambda: reverse('some_viewname'))
    def do_redirect(request):
        ...

    """
    def outer(f):
        @wraps(f)
        def inner(request, *args, **kwargs):
            f(request, *args, **kwargs)
            return HttpResponsePermanentRedirect(url if not callable(url) else url())
        return inner
    return outer


def redirect(url):
    """
    Executes a HTTP 302 redirect after the view finishes processing. If a value is 
    returned, it is ignored. Allows for the view url to be callable so the
    reverse() lookup can be used.
    
    @redirect('http://www.google.com/')
    def goto_google(request):
        pass

    @redirect(lambda: reverse('some_viewname'))
    def do_redirect(request):
        ...
    
    """
    def outer(f):
        @wraps(f)
        def inner(request, *args, **kwargs):
            f(request, *args, **kwargs)
            return HttpResponseRedirect(url if not callable(url) else url())
        return inner
    return outer

More like this

  1. Decorator to logout user based on a test and/or redirect to another url by vemubalu 3 years, 4 months ago
  2. Internet Explorer Redirect Decorator by johnboxall 5 years, 6 months ago
  3. Decorator to ease dynamic redirections in Django by david_bgk 5 years, 2 months ago
  4. SWFUpload auth decorator by debrice 5 years, 1 month ago
  5. Decorator for enabling views only when developing by damd 3 years, 8 months ago

Comments

zymen (on July 13, 2010):

Why dont you use django.views.generic.simple.redirect_to view?

#

bryanpieper (on July 13, 2010):

These decorators are supplemental to the generic django views. They allow you to process any number of items before the redirection.

#

zymen (on July 14, 2010):

Yes, but what is a difference between:

def view1(request): do_actions redirect_to(...)

and

@redirect(...) def view2(request): do_actions

I don't know what others think about it, but for me this snippet doesn't contain 'value added'.

#

Verurteilt (on July 19, 2013):

@zymen This can be veru helpful when you return a pdf output and you need to redirect after the return pdf

#

(Forgotten your password?)