diff options
| author | Malcolm Tredinnick <malcolm.tredinnick@gmail.com> | 2006-09-22 01:44:28 +0000 |
|---|---|---|
| committer | Malcolm Tredinnick <malcolm.tredinnick@gmail.com> | 2006-09-22 01:44:28 +0000 |
| commit | 6be701eba172a2ca71aaff0f9efe5796b30ca066 (patch) | |
| tree | 51e7e64293dfb64a9ec62893e61674a3b795febc | |
| parent | 3efd4dcd2d03c235a1b28d382466440a33c271f9 (diff) | |
Fixed #2629 -- Added a permission_required decorator to
django.contrib.auth.decorator. Thanks, dummy@habmalnefrage.de.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@3779 bcc190cf-cafb-0310-a4f2-bffc1f526a37
| -rw-r--r-- | django/contrib/auth/decorators.py | 8 | ||||
| -rw-r--r-- | docs/authentication.txt | 22 |
2 files changed, 30 insertions, 0 deletions
diff --git a/django/contrib/auth/decorators.py b/django/contrib/auth/decorators.py index 0102496a33..8164d8314e 100644 --- a/django/contrib/auth/decorators.py +++ b/django/contrib/auth/decorators.py @@ -26,3 +26,11 @@ login_required.__doc__ = ( to the log-in page if necessary. """ ) + +def permission_required(perm, login_url=LOGIN_URL): + """ + Decorator for views that checks if a user has a particular permission + enabled, redirectiing to the log-in page if necessary. + """ + return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url) + diff --git a/docs/authentication.txt b/docs/authentication.txt index f161e9d357..e7adbfb6bf 100644 --- a/docs/authentication.txt +++ b/docs/authentication.txt @@ -456,6 +456,10 @@ As a shortcut, you can use the convenient ``user_passes_test`` decorator:: # ... my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'))(my_view) +We are using this particular test as a relatively simple example, however be +aware that if you just want to test if a permission is available to a user, +you can use the ``permission_required()`` decorator described below. + Here's the same thing, using Python 2.4's decorator syntax:: from django.contrib.auth.decorators import user_passes_test @@ -488,6 +492,24 @@ Example in Python 2.4 syntax:: def my_view(request): # ... +The permission_required decorator +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Since checking whether a user has a particular permission available to them is a +relatively common operation, Django provides a shortcut for that particular +case: the ``permission_required()`` decorator. Using this decorator, the +earlier example can be written as:: + + from django.contrib.auth.decorators import permission_required + + def my_view(request): + # ... + + my_view = permission_required('polls.can_vote')(my_view) + +Note that ``permission_required()`` also takes an optional ``login_url`` +parameter. + Limiting access to generic views -------------------------------- |
