如何使用django自定义装饰器

How to use django custom decorator

我有很多方法需要授权。因此,我不想一遍又一遍地编写相同的代码,而是想简化它。据我了解,我无法使用 @login_required,因为它会重定向到我没有的登录页面。 (用户通过所有模板中包含的下拉菜单登录系统)。我只想提高 PermissionDenied 而不进行任何重定向。

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

一个解决方案是使用自定义装饰器:

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

但是需要在里面传递一个函数。所以我不能只将 @login_required_no_redirect() 放在方法之上。它需要将一些函数作为参数传递。我从哪里得到它?没有参数的django装饰器很多,类似的怎么写?

此致,

Django 已经为此提供了一个 @permission_required 装饰器。

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.