Why second user login redirects me to /accounts/profile/ url?

北城余情 提交于 2019-12-03 04:15:19
Traian

django.contrib.auth.views.login redirects you to accounts/profile/ right after you log in.
You may want to set LOGIN_REDIRECT_URL inside your settings.py file to anything you like..

dani herrera

Explained in doc:

(accounts/profile/ is ...) The URL where requests are redirected after login when the contrib.auth.login view gets no next parameter.

Because you are yet authenticated your request is redirected to this url. To avoid redirect you should logout user before send it to user/login, create your custom login view or append Next parameter.

@CpS provided very good solution, I just want to enhance it a little bit:

For example, you have following urls:

urlpatterns = [
    # django's login/logout
    url(r'login/$', 'django.contrib.auth.views.login', name='login'),
    url(r'logout/$', 'django.contrib.auth.views.logout', name='logout'),
    url(r'logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'),
    url(r'^$', views.dashboard, name='dashboard')
]

and dashboard.html is where you want to redirect after successful login, then you can modify your settings.py file accordingly:

from django.core.urlresolvers import reverse_lazy

LOGIN_REDIRECT_URL=reverse_lazy('dashboard')
LOGIN_URL=reverse_lazy('login')
LOGOUT_URL=reverse_lazy('logout')

We are using reverse_lazy() to build the URLs dynamically. The reverse_lazy() function reverses URLs just like reverse() does, but you can use it when you need to reverse URLs before your project's URL configuration is loaded.

check your 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>

good luck~

All of this did not work for me. I used a JavaScript solution:

In the login.html (where the social login buttons are) I put this script which stores next in local storage::

<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>

In the page where the users are being redirected to I used the following script to redirect:

$(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..
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!