[docs]defuser_passes_test(test_func,login_url=None,redirect_field_name=REDIRECT_FIELD_NAME):""" Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """defdecorator(view_func):@wraps(view_func)def_wrapped_view(request,*args,**kwargs):iftest_func(request.user):returnview_func(request,*args,**kwargs)path=request.build_absolute_uri()resolved_login_url=resolve_url(login_urlorsettings.LOGIN_URL)# If the login url is the same scheme and net location then just# use the path as the "next" url.login_scheme,login_netloc=urlparse(resolved_login_url)[:2]current_scheme,current_netloc=urlparse(path)[:2]if((notlogin_schemeorlogin_scheme==current_scheme)and(notlogin_netlocorlogin_netloc==current_netloc)):path=request.get_full_path()fromdjango.contrib.auth.viewsimportredirect_to_loginreturnredirect_to_login(path,resolved_login_url,redirect_field_name)return_wrapped_viewreturndecorator

[docs]deflogin_required(function=None,redirect_field_name=REDIRECT_FIELD_NAME,login_url=None):""" Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """actual_decorator=user_passes_test(lambdau:u.is_authenticated,login_url=login_url,redirect_field_name=redirect_field_name)iffunction:returnactual_decorator(function)returnactual_decorator

[docs]defpermission_required(perm,login_url=None,raise_exception=False):""" Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised. """defcheck_perms(user):ifisinstance(perm,str):perms=(perm,)else:perms=perm# First check if the user has the permission (even anon users)ifuser.has_perms(perms):returnTrue# In case the 403 handler should be called raise the exceptionifraise_exception:raisePermissionDenied# As the last resort, show the login formreturnFalsereturnuser_passes_test(check_perms,login_url=login_url)