How to write a custom decorator in django?


Question

The problem -

@is_premium_user
def sample_view:
          .......
          ......

I want certain views accesible to only the premium users of the website.
And how can I use this decorator across various applications in my project?

1
49
3/29/2011 7:23:27 AM

Accepted Answer

You don't have to write your own decorator for this as user_passes_test is already included in Django.

And there's a snippet (group_required_decorator) that extends this decorator and which should be pretty appropriate for your use case.

If you really want to write your own decorator then there's a lot of good documentation on the net.

And well, to (re-) use the decorator just put your decorator in a module on your path and you can import it from any other module.

49
12/1/2016 7:23:09 PM

Played around with the various links above and couldn't get them working and then came across this really simple one which I adapted. http://code.activestate.com/recipes/498217-custom-django-login_required-decorator/

from functools import wraps
from django.http import HttpResponseRedirect

def authors_only(function):
  @wraps(function)
  def wrap(request, *args, **kwargs):

        profile = request.user.get_profile()
        if profile.usertype == 'Author':
             return function(request, *args, **kwargs)
        else:
            return HttpResponseRedirect('/')

  return wrap

Using @wraps is better than manually overriding like doing wrap.__doc__ = fn.__doc__. Amongst other things, it ensures your wrapper function gets the same name as the wrapped function.

See https://docs.python.org/2/library/functools.html


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon