django LOGIN_REDIRECT_URL具有动态值
-
05-07-2019 - |
题
我正在尝试将用户重定向到包含其用户名的网址(例如 http:// domain / username / ),并试图弄清楚如何做到这一点。我正在使用django.contrib.auth进行用户管理,所以我尝试在设置中使用LOGIN_REDIRECT_URL:
LOGIN_REDIRECT_URL = '/%s/' % request.user.username # <--- fail..
但它似乎只接受固定的字符串,而不是在用户登录后确定的东西。我怎么能完成这个呢?
解决方案
解决方案是重定向到像'/ userpage /'这样的静态路由,并将其重定向到最终的动态页面。
但我认为真正的解决方案是制作一个能够满足您真正需要的新视图。
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 /主题/ AUTH /#认证中的Web-请求
有关重写视图的更多信息。这就是文档如何覆盖这种事情。
其他提示
在您自己的自定义视图中包装身份验证视图,并在身份验证成功时重定向到您想要的任何位置。
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.urlresolvers import reverse
def login(request):
template_response = auth.views.login(request)
if isinstance(template_response, HttpResponseRedirect) and template_response.url == '/accounts/profile/':
return HttpResponseRedirect(reverse('user', args=(request.user.username,)))
return template_response
另一种方法是使用查询参数 next
来指示登录后重定向到的位置。
<a href="{% url 'login' %}?next={{ request.path }}">sign in</a>
使用基于类的 django.contrib.auth.views.LoginView
,您现在可以简单地覆盖 get_success_url
:
<强> urls.py:强>
url(r'^login
<强> views.py 强>
class MyLoginView(LoginView):
def get_success_url(self):
return reverse('my_account', args=[self.request.user.username])
, MyLoginView.as_view(), name='login'),
url(r'^users/(?P<username>[a-zA-Z0-9]+)
<强> views.py 强>
<*>, MyAccountView.as_view(), name='my_account'),
<强> views.py 强>
<*>不隶属于 StackOverflow