[Django]-Is using view decorators to handle user permissions bad practice?

2đź‘Ť

âś…

The text you mention is debatable at best – at least in it’s formulation:

Avoid external dependencies in the decorator itself (e.g. don’t rely on files, sockets, database connections, etc.), since they might not be available when the decorator runs (at import time, perhaps from pydoc or other tools).

(…)

Decorators are a special case of “top level code”

This only applies to the “outer” part of the decorator function, not the code within the wrapper function (usually) returned by the decorator, ie:

def mydecorator(func):
    print("""
       this is the outer decorator code 
       and will be executed when the decorator
       is applied (most often - but not necessarily
       - at import time)
       """
       )
       def wrapper(*args, **kw):
           print("""
              this is the inner decorator code     
              which is only executed when the
              decorated function is called,
              so here it's safe to do whatever
              you would do in the decorated function.
              """
              )
              return func(*args, **kw)
      return wrapper       

IOW, what you’re doing (using decorators in views to check whether the user is allowed to access the content) is not only perfectly ok and a canonical example of what decorators are for, but it’s even the official way to handle this in Django, cf Davide Pizzolato’s answer.

3đź‘Ť

In Django use the user_passes_test or permission_required decorator is the right way to do it.

from django.contrib.auth.decorators import user_passes_test, permission_required

@user_passes_test(lambda user: user.is_superuser)
@permission_required('your_perm')
def my_view(request):
    # code

Leave a comment