【问题标题】:Django throws a 302 error when I try to redirect a user after password change更改密码后尝试重定向用户时,Django 抛出 302 错误
【发布时间】:2023-03-16 17:41:01
【问题描述】:

我有一个 view 来处理用户的密码更改

@csrf_exempt
def change_password(request):
    if request.method == "POST":
        user_request = json.loads(request.body.decode('utf-8'))
        try:
            u = User.objects.get(username=user_request.get("user"))
            u.set_password(user_request.get("password"))
            u.save()
        except Exception as e:
            print(e)
            return HttpResponse("Failure")
        return HttpResponseRedirect('/')

这确实会更改用户的密码,因为下次我必须登录时,我必须提供新密码。但它不会立即将用户重定向到主页(反过来会重定向到登录页面因为用户已注销)。

我对下面给出的登录有类似的看法

@csrf_exempt
def login_view(request):
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/')
        else:
            return render(request, "login.html")
    else:
        return render(request, "login.html")

但如果认证成功,它会将用户重定向到主页。

那么为什么当用户更改密码时没有发生任何重定向?我得到的是302 状态码。

【问题讨论】:

  • 显示状态信息。
  • 你应该在末尾附加一个斜杠(request, "login.html/")
  • @dEv 不,绝对不是。
  • 您是否通过 ajax 调用调用 change_password 视图?
  • @thebjorn 是的,我是。

标签: python django url-redirection


【解决方案1】:

“302 Found”重定向。它在 HTTP 响应中包含一个“Location”标头,告诉浏览器去哪里。

【讨论】:

  • 好的,我明白了。所以如果我提到了一个/ 指示它进入主页,为什么它不起作用?
  • 恐怕我无法回答。对我来说这听起来像是一个客户端问题,但我不是网络开发人员,所以这超出了我的理解范围。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
相关资源
最近更新 更多