装饰器login_required将游客身份引导至登录页面,登录成功后跳转到目的页面

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')

装饰器@login_required,会跳转到django设置的默认路径:‘/accounts/login/’,在setting.py中进行修改,跳转到登录页的路由

setting.py

LOGIN_URL ='/login/'

第一次请求:http://127.0.0.1:8999/home/

转到'http://127.0.0.1:8999/login/?next=home'

登录成功,转到'http://127.0.0.1:8999/home/'

如果是ajax请求如何实现登录成功后自动跳回第一次请求的路径:

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=someone@example.com

类视图中如何使用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)
12-24 11:37