django使用@login_required时出现重定向次数过多问题是怎么回事

报错如下:

图片说明

目录如下:

图片说明

index的views.py:
图片说明

login的views.py:

from django.shortcuts import render, redirect
from .forms import *


# Create your views here.


def login_views(request):
    if request.method == 'GET':
        # 获取请求源地址,如果没有的话则获取'/'
        url = request.META.get('HTTP_REFERER', '/')
        # print("请求源地址:"+url)
        # 判断session中是否有uid和uname
        if 'uid' in request.session and 'uname' in request.session:
            return redirect(url)
        else:
            # 判断cookie中是否有uid和uname,
            if 'uid' in request.COOKIES and 'uname' in request.COOKIES:
                # 如果有的话则取出来并保存进session,再回首页
                uid = request.COOKIES['uid']
                uname = request.COOKIES['uname']
                request.session['uid'] = uid
                request.session['uname'] = uname
                return redirect(url)
            else:
                form = LoginForm()
                # 构建响应对象,并将url保存进cookies
                resp = render(request, 'login.html', locals())
                resp.set_cookie('url', url)
                return resp
    else:
        # post请求
        # 获取请求源地址
        url = request.META.get('HTTP_REFERER', '/')
        # 接收uname和upwd判断是否登录成功
        uname = request.POST['uname']
        upwd = request.POST['upwd']
        user_name = Users.objects.filter(uname=uname)

        users = Users.objects.filter(uname=uname, upwd=upwd)
        # 如果成功继续向下执行,否则回到登录页
        if users:
            # 登录成功,将id和uname保存进session
            id = users[0].id
            request.session['uid'] = id
            request.session['uname'] = uname
            # 如果有记住密码则将数据保存进cookies
            # 先从cookies中将url的值获取出来
            url = request.COOKIES.get('url', '/')
            resp = redirect(url)
            # 如果url存在于cookies中的话,则将url从cookies中删除出去
            if 'url' in request.COOKIES:
                resp.delete_cookie('url')
            if 'isSave' in request.POST:
                expires = 60 * 60 * 24 * 365
                resp.set_cookie('uid', id, expires)
                resp.set_cookie('uname', uname, expires)
            return resp
        else:
            # 登录失败,回到登录页面
            message = '登录失败!'
            return redirect('/login/')
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问