gpt4 book ai didi

django LOGIN_REDIRECT_URL具有动态值

转载 作者:行者123 更新时间:2023-12-04 05:38:13 26 4
gpt4 key购买 nike

我正在尝试将用户重定向到包含他的用户名的网址(例如http://domain/username/),并试图弄清楚如何做到这一点。我正在使用django.contrib.auth进行用户管理,因此我尝试在设置中使用LOGIN_REDIRECT_URL:

LOGIN_REDIRECT_URL = '/%s/' % request.user.username # <--- fail..

但它似乎只接受固定的字符串,而不接受在用户登录后确定的字符串。如何仍然可以做到这一点?

最佳答案

一种解决方案是重定向到静态路由,例如“/userpage/”,然后将其重定向到最终的动态页面。

但是我认为真正的解决方案是创建一个新 View ,以实现您真正想要的功能。

from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect

def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
HttpResponseRedirect('/%s/'%username)
else:
# Return a 'disabled account' error message
else:
# Return an 'invalid login' error message.

http://docs.djangoproject.com/en/dev/topics/auth/#authentication-in-web-requests

有关重写 View 的更多信息。这就是文档所说的覆盖这种事情的方式。

关于django LOGIN_REDIRECT_URL具有动态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1608261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com