简体   繁体   中英

How to use django custom decorator

I have a lot of methods that require authorization. So instead of writting the same code over and over I wanna simplify it. As I understood I can't use @login_required as it redirects to login page, which I don't have. (user logs in into system via dropdown menu included in all templates). I just wanna raise PermissionDenied without any redirecting.

get_profile(request):
    if request.user.is_authenticated():
       do things
    else:
       raise PermisionDenied

One solution is use a custom decorator:

def login_required_no_redirect(f):
    def wrap(request, *args, **kwargs):
        if request.user.is_authenticated():
            return f(request, *args, **kwargs)
        else:
            raise PermissionDenied

    wrap.__doc__ = f.__doc__
    wrap.__name__ = f.__name__
    return wrap

But it requires to pass a function inside. So I can't just place @login_required_no_redirect() above the method. It requires to pass some function as a parameter. Where do I get it? There're a lot of django decorators without parameters, how do I write the similar one?

Best regards,

Django already has a @permission_required decorator for this.

If the raise_exception parameter is given, the decorator will raise PermissionDenied, prompting the 403 (HTTP Forbidden) view instead of redirecting to the login page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM