Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a custom decorator in django?

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?

like image 808
user677990 Avatar asked Mar 29 '11 07:03

user677990


People also ask

How do I create a custom decorator in Python?

To create a decorator function in Python, I create an outer function that takes a function as an argument. There is also an inner function that wraps around the decorated function. To use a decorator ,you attach it to a function like you see in the code below.

What is Django decorator?

Decorators are a way to restrict access to views based on the request method or control caching behaviour. This is particularly useful when you want to separate logged-in users from unauthenticated users or create an admin page that only privileged users can access.

What is decorator syntax?

Decorators provide a simple syntax for calling higher-order functions. By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.


1 Answers

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

like image 75
PhoebeB Avatar answered Sep 30 '22 17:09

PhoebeB