[Answer]-Django — Requiring a certain access level for pages

1👍

Python decorators have access to the wrapped functions arguments.

With this knowledge we could alter our decorator like so, to have access to the request.user object. This is assuming the first argument to my_view() will always be the request object.

def required_access(access=None):
    def wrap(func):
        def inner(*args, **kwargs):
            if access <= args[0].user.access:
                print 'The user can access this page, their access level is greater than or equal to whats required.'
            else:
                print 'This page cannot be viewed, their access level is too low.'
            return func(*args, **kwargs)
        return inner
    return wrap

@login_required
@required_access(access=300)
def foo(request):
    return render(request, 'bar.html', {})

0👍

Try this..

https://docs.djangoproject.com/en/1.7/topics/auth/default/#limiting-access-to-logged-in-users-that-pass-a-test

from django.contrib.auth.decorators import user_passes_test

def email_check(user):
    return user.email.endswith('@example.com')

@user_passes_test(email_check)
def my_view(request):
    [...]

Leave a comment