2 from functools
import update_wrapper
, wraps
4 from django
.utils
.functional
import update_wrapper
, wraps
# Python 2.4 fallback.
6 from django
.contrib
.auth
import REDIRECT_FIELD_NAME
7 from django
.http
import HttpResponseRedirect
8 from django
.utils
.decorators
import available_attrs
9 from django
.utils
.http
import urlquote
12 def user_passes_test(test_func
, login_url
=None, redirect_field_name
=REDIRECT_FIELD_NAME
):
14 Decorator for views that checks that the user passes the given test,
15 redirecting to the log-in page if necessary. The test should be a callable
16 that takes the user object and returns True if the user passes.
19 from django
.conf
import settings
20 login_url
= settings
.LOGIN_URL
22 def decorator(view_func
):
23 def _wrapped_view(request
, *args
, **kwargs
):
24 if test_func(request
.user
):
25 return view_func(request
, *args
, **kwargs
)
26 path
= urlquote(request
.get_full_path())
27 tup
= login_url
, redirect_field_name
, path
28 return HttpResponseRedirect('%s?%s=%s' % tup
)
29 return wraps(view_func
, assigned
=available_attrs(view_func
))(_wrapped_view
)
33 def login_required(function
=None, redirect_field_name
=REDIRECT_FIELD_NAME
):
35 Decorator for views that checks that the user is logged in, redirecting
36 to the log-in page if necessary.
38 actual_decorator
= user_passes_test(
39 lambda u
: u
.is_authenticated(),
40 redirect_field_name
=redirect_field_name
43 return actual_decorator(function
)
44 return actual_decorator
47 def permission_required(perm
, login_url
=None):
49 Decorator for views that checks whether a user has a particular permission
50 enabled, redirecting to the log-in page if necessary.
52 return user_passes_test(lambda u
: u
.has_perm(perm
), login_url
=login_url
)