Login

LoginRequired class-based view decorator

Author:
mjumbe
Posted:
July 25, 2011
Language:
Python
Version:
1.3
Score:
2 (after 2 ratings)

Apply the login_required decorator to all the handlers in a class-based view that delegate to cls.dispatch.

Optional arguments:

  • redirect_field_name = REDIRECT_FIELD_NAME
  • login_url = None

See the documentation for the login_required method for more information about the keyword arguments.

Usage:

@LoginRequired
class MyListView (ListView):
    ...
 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
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator


def LoginRequired(cls=None, **login_args):
    """
    Apply the ``login_required`` decorator to all the handlers in a class-based
    view that delegate to the ``dispatch`` method.
    
    Optional arguments
    ``redirect_field_name`` -- Default is ``django.contrib.auth.REDIRECT_FIELD_NAME``
    ``login_url`` -- Default is ``None``

    See the documentation for the ``login_required`` [#]_ for more information
    about the keyword arguments.
    
    Usage:
      @LoginRequired
      class MyListView (ListView):
        ...
    
    .. [#] https://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator
    
    """
    if cls is not None:
        # Check that the View class is a class-based view. This can either be
        # done by checking inheritance from django.views.generic.View, or by
        # checking that the ViewClass has a ``dispatch`` method.
        if not hasattr(cls, 'dispatch'):
            raise TypeError(('View class is not valid: %r.  Class-based views '
                             'must have a dispatch method.') % cls)
        
        original = cls.dispatch
        modified = method_decorator(login_required(**login_args))(original)
        cls.dispatch = modified
        
        return cls
    
    else:
        # If ViewClass is None, then this was applied as a decorator with
        # parameters. An inner decorator will be used to capture the ViewClass, 
        # and return the actual decorator method.
        def inner_decorator(inner_cls):
            return LoginRequired(inner_cls, **login_args)
        
        return inner_decorator

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

mozillalives (on July 25, 2011):

I don't see what usefulness this provides over the pre-existing login_required decorator.

#

mjumbe (on July 25, 2011):

It's just a way of encapsulating something I was doing a lot in my code. Instead of doing this:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

class ProtectedView(TemplateView):
    template_name = 'secret.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(ProtectedView, self).dispatch(*args, **kwargs)

I can do this:

from django.views.generic import TemplateView
from myapp.utils.decorators import LoginRequired

@LoginRequired
class ProtectedView(TemplateView):
    template_name = 'secret.html'

(Example borrowed from Decorating the class )

#

Please login first before commenting.