Decorator login_required will guide a visitor to the login page, the login is successful jump to the destination page
url.py
path('login/',views.login),
path('home/',views.home),
views.py
from django.contrb.auth.decorators import login_required
@login_required
def home(request):
return render(request,'home.html')
Decorator @login_required, it will jump to the default path django settings: '/ accounts / login /', modified in setting.py, a jump to the login page of the routing
setting.py
LOGIN_URL ='/login/'
The first request:http://127.0.0.1:8999/home/
Go to'http://127.0.0.1:8999/login/?next=home'
Login successful, go to'http://127.0.0.1:8999/home/'
If the request is ajax how to automatically jump back to the path of the first request after a successful login:
success:function(response){
if(resonse.user){
if(location.search){
//间接进入login时,转回
location.href=location.search.slice(6)
//直接进入login时,转到首页
else{location.href='/home/'}
}
}
}
// search 属性是一个可读可写的字符串,可设置或返回当前 URL 的查询部分(问号 ? 之后的部分)。
// 假设当前的URL就是http://www.runoob.com/submit.htm?email=someone@ example.com
// location.search:[email protected]
Class View on how to use login_required
from django.views import View
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class Myview(View):
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)