Skip to content

Commit

Permalink
[1.7.x] Fixed #24501 -- Improved auth.decorators.user_passes_test() e…
Browse files Browse the repository at this point in the history
…xample.

Backport of fca14cd from master
  • Loading branch information
Matt Seymour authored and timgraham committed Mar 24, 2015
1 parent b46643a commit 388dc33
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions docs/topics/auth/default.txt
Original file line number Diff line number Diff line change
Expand Up @@ -406,11 +406,12 @@ The simple, raw way to limit access to pages is to check
<django.contrib.auth.models.User.is_authenticated()>` and either redirect to a
login page::

from django.conf import settings
from django.shortcuts import redirect

def my_view(request):
if not request.user.is_authenticated():
return redirect('/login/?next=%s' % request.path)
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
# ...

...or display an error message::
Expand Down Expand Up @@ -497,16 +498,20 @@ essentially the same thing as described in the previous section.

The simple way is to run your test on :attr:`request.user
<django.http.HttpRequest.user>` in the view directly. For example, this view
checks to make sure the user has an email in the desired domain::
checks to make sure the user has an email in the desired domain and if not,
redirects to the login page::

from django.shortcuts import redirect

def my_view(request):
if not request.user.email.endswith('@example.com'):
return HttpResponse("You can't vote in this poll.")
return redirect('/login/?next=%s' % request.path)
# ...

.. function:: user_passes_test(func, [login_url=None])

As a shortcut, you can use the convenient ``user_passes_test`` decorator::
As a shortcut, you can use the convenient ``user_passes_test`` decorator
which performs a redirect when the callable returns ``False``::

from django.contrib.auth.decorators import user_passes_test

Expand Down

0 comments on commit 388dc33

Please sign in to comment.