为什么第二个用户登录将我重定向到/accounts/profile/url



我正在使用django内置的用户登录:

url(r'^user/login/$', 'django.contrib.auth.views.login', {'template_name': 'users/templates/login.html'}, name='user-login'),

登录后,当我再次获得用户/登录时,我可以第二次登录。我提交表格并获得:

当前的URL,帐户/profile/与其中任何一个不匹配。

我没有在urls.py中声明此URL。

我做错了什么?为什么框架要重定向到此URL?

django.contrib.auth.views.login登录后立即将您重定向到accounts/profile/
您可能需要将settings.py中的LOGIN_REDIRECT_URL设置为您喜欢的任何东西..

在doc中解释:

(帐户/profile/is ...)登录后重定向的URL当 cons.auth.login视图没有下一个参数。

因为您尚未经过身份验证,您的请求已重定向到此URL。为避免重定向,您应该在将用户发送到user/login之前注销用户,创建自定义登录视图或附加下一个参数。

检查您的登录.html

<form method="post" action=".">
    ~blah~
    <input type="hidden" name="next" value="/"><!-- login.html must send "next" parameter, and "next" parameter value is url that you want to redirect.  -->
    ~blah~
</form>

祝你好运〜

所有这些对我不起作用。我使用了JavaScript解决方案:

在login.html中(社交登录按钮所在),我将此脚本放在本地存储中存储在本地存储中::

<script>
// Check for local storage
if (typeof(Storage) !== "undefined") {
    var h = window.location.href;
    if (h.indexOf("next") > 0){
        var tokens = h.split("=");
        var nextUrl = tokens[1];
        for(i = 2;i< tokens.length;i++){
            nextUrl += ("=" + tokens[i]);
        }
        localStorage.setItem("next",nextUrl);
    }
}
</script>

在重定向到用户的页面中,我使用以下脚本重定向:

$(document).ready(function () {
    // Check for local storage
    if (typeof(Storage) !== "undefined") {
            var nextUrl = localStorage.getItem("next");
            if (nextUrl.length > 0){
                localStorage.setItem("next","");
                window.location = nextUrl;
            }
    }
    else {
        // Sorry! No web storage support..
    }
}

使用django中的视图构建时。您已成功登录。Django.contrib.auth.views.login,是您使用的Django视图。

它具有称为login_redirect_url的参数,该参数在登录后自动重定向您。

wich是URL或命名的URL模式,登录后登录后重定向的URL模式,当登录未获得下一个获取参数时。说文档

https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-login_redirect_url

尝试将其添加到您用于登录的HTML页面。

两种方式,您可以使用logout; login_redirect_url&quot;或

只需使用将@login_required Decorator

重定向到视图方法的URL

示例

在登录后进行第二次登录(以下代码在logout.html中)

<a href ="/">Login again </a>

在Views.py

@login_required
def home(request):
  return HttpResponse("Welcome")

最新更新