How to create a custom decorator in Django?

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("https://stackoverflow.com/")

  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

Leave a Comment