You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django登出未清除浏览器Cookie,导致二次登录报错问题

问题分析与解决方案

核心问题

  1. 登录视图的错误查询逻辑:
    代码中Customer.objects.get(email=email, password=password)直接用明文密码查询用户,但Django默认会对密码做哈希存储,这行代码必然抛出DoesNotExist异常,导致登录成功后返回500错误,同时干扰后续登录流程。

  2. 登出视图删除Cookie参数不匹配:
    调用delete_cookie时未指定与Cookie设置一致的path(默认是/),浏览器会因参数不匹配拒绝删除Cookie,旧的sessionid残留会导致二次登录时出现冲突报错。

修正后的代码

登录视图修正

@csrf_exempt
def post(self, request):
    try:
        email = request.data.get('email')
        password = request.data.get('password')
        user = authenticate(request, username=email, password=password)
        if user is not None:
            request.session.set_expiry(86400*30) # 30 days
            login(request, user)
            # 已通过authenticate验证,直接用邮箱查询Customer即可
            user_obj = Customer.objects.get(email=email)
            return Response({'user_id': user_obj.id}, status=status.HTTP_200_OK)
        else:
            return Response({'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
    except Customer.DoesNotExist:
        return Response({'message': 'User not found'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response("Internal Server Error", status=status.HTTP_500_INTERNAL_SERVER_ERROR)

登出视图修正

class LogoutView(APIView):
    @csrf_exempt
    def post(self, request):
        try:
            logout(request)
            response = Response({'message': 'Logout successful'}, status=status.HTTP_200_OK)
            # 指定与Cookie设置一致的根路径,确保浏览器能正确删除
            response.delete_cookie('sessionid', path='/')
            response.delete_cookie('csrftoken', path='/')
            # 若站点使用HTTPS,需添加secure=True参数
            # response.delete_cookie('sessionid', path='/', secure=True)
            # response.delete_cookie('csrftoken', path='/', secure=True)
            # 有自定义域名时,补充domain参数,比如domain='yourdomain.com'
            return response
        except Exception as e:
            print('error logout ==>', e)
            return Response("Internal Server Error", status=status.HTTP_500_INTERNAL_SERVER_ERROR)

额外说明

  • 登录时authenticate已验证密码有效性,无需再用密码查询用户,避免哈希密码导致的查询失败。
  • 删除Cookie时,path、domain、secure等参数必须与设置Cookie时完全一致,否则浏览器不会执行删除操作。
  • 建议统一使用Response,避免混合JsonResponse和Response,保持代码风格统一。

内容的提问来源于stack exchange,提问作者gautam thakur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 23:29:54