This article describes how to restrict access by logged-on users in Django. Django is the most popular Python development framework, for more information, see the section that users need to access the site for many reasons.
A simple and original method is to check request. user. is_authenticated () and redirect to the login page:
From django. http import HttpResponseRedirectdef my_view (request): if not request. user. is_authenticated (): return HttpResponseRedirect ('/accounts/login /? Next = % s' % request. path )#...
Or an error message is displayed:
Def my_view (request): if not request. user. is_authenticated (): return render_to_response ('myapp/login_error.html ')#...
As a shortcut, you can use the convenient login_required modifier:
From django. contrib. auth. decorators import login_required @ login_requireddef my_view (request ):#...
Login_required:
If the user does not log on, redirect to/accounts/login/and pass the current absolute URL as next in the query string. for example:/accounts/login /? Next =/polls/3 /.
If the user has logged on, the View function is executed normally. The View code assumes that the user has logged on.
=