我正在创建一个登录视图,在该视图中,如果不是用户登录,则登录后应先登录到同一页面,然后再登录至其他网址,但始终应转到其他网址,尽管应先转到第一个重定向< / p>
views.py
def login_page(request):
form = LoginForm(request.POST or None)
context = {
"form": form
}
next_get_url= request.GET.get('next')
next_post_url= request.POST.get('next')
redirect_path = next_get_url or next_post_url or None
if form.is_valid():
print(form.cleaned_data)
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(request, username=username, password=password)
print(user)
if user is not None:
login(request, user)
if is_safe_url(redirect_path, request.get_host()):
return(redirect(redirect_path))
else:
return (redirect('/'))
else:
print ("Error")
return render(request, "accounts/login.html",context)
forms.py:
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
我的意思是总是这样:
else:
return (redirect('/'))
在这种情况下:
if is_safe_url(redirect_path, request.get_host()):
return(redirect(redirect_path))
找到的所有尝试和解决方案都无法解决任何帮助!并预先感谢
答案 0 :(得分:0)
您应该使用
redirect_path = next_get_url or next_post_url or "/"
因为如果您将None
传递给is_safe_url
,它将返回False
,因为它只使用有效的网址。
答案 1 :(得分:0)
首先,Django带有LoginView
,可为您处理重定向。最好使用它而不是编写自己的视图。
如果您确实编写了自己的视图,则需要将redirect_path
包含在context
字典here is where Django does is中,然后需要将其作为隐藏字段包含在登录名中表单(请参见LoginView
的示例模板in the docs:
<form ...>
...
<input type="submit" value="login">
<input type="hidden" name="next" value="{{ next }}">
</form>
答案 2 :(得分:0)
尝试使用此渲染方法
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
render(request , 'bootstrap/page_learn.html')
else:
# Return an 'invalid login' error message.
render(request , 'bootstrap/page_learn.html')