Django登录成功后不跳转至首页问题排查与修复请求
Let's break down what's happening here and fix this frustrating login quirk step by step:
Problem Recap
I have a login interface that previously worked correctly: after successful verification, it should display user details on the same base URL (127.0.0.1:8000). Now, when entering the correct username and password, the system returns a 302 response code (
HTTP POST /login/ 302 [0.60, 127.0.0.1:53864]), but doesn't initiate a redirect— the page keeps loading. Strangely, when I refresh the current tab or open a new tab, the user is correctly logged in and the details are displayed. I haven't modified any login-related functions, only recently added a password reset feature unrelated to login.
Key Fixes to Implement
1. Fix URL Pattern Matching
Your current login URL lacks an end anchor ($), which means it will match any URL starting with login/ (like login/reset from your new password reset flow). This can cause unexpected routing conflicts.
Update your urls.py:
urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.IndexView.as_view(), name='index'), # Add ^ at the start and $ at the end for exact matching url(r'^login/$', views.user_login, name='login'), ]
2. Replace Unreliable Relative Path Redirects
Using ../ in HttpResponseRedirect is risky because it depends on the current URL context. Your new password reset routes might have changed this context, breaking the relative path.
Revise your user_login function to use named URLs:
def user_login(request): field = None if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) try: field = UserModel.objects.get(user__username=username) if user: if user.is_active: login(request, user) # This part is already correct - uses named URL for index return HttpResponseRedirect(reverse('index')) else: messages.error(request, 'Username or password is incorrect') # Use reverse('login') instead of ../ return HttpResponseRedirect(reverse('login')) else: print(f"Error logging in with password: {password}") messages.error(request, 'Invalid username/password combination') return HttpResponseRedirect(reverse('login')) except Exception: messages.error(request, 'Entered username does not belong to any account') return HttpResponseRedirect(reverse('login')) else: return render(request, 'app/login.html', {})
3. Check for AJAX Form Submission (Hidden Culprit)
If your login form is being submitted via AJAX (fetch/axios/JQuery) instead of a standard HTML submit, the browser won't automatically follow 302 redirects. This is a common side effect if your password reset feature added new JavaScript that affects the login form.
Fix for AJAX submission (example with fetch):
fetch('/login/', { method: 'POST', headers: { 'X-CSRFToken': getCookie('csrftoken'), // Don't forget the CSRF token }, body: new FormData(document.getElementById('login-form')) }) .then(response => { if (response.redirected) { window.location.href = response.url; // Manually trigger the redirect } }) .catch(error => console.error('Login error:', error));
4. Verify Password Reset Didn't Alter Session Settings
Even if you didn't touch login code, your password reset feature might have modified Django session configurations or middleware. Check:
settings.pyfor changes toSESSION_COOKIE_SECURE,SESSION_COOKIE_HTTPONLY, or theMIDDLEWARElist- Ensure password reset views aren't inadvertently clearing or modifying user sessions
内容的提问来源于stack exchange,提问作者Prajwal Kulkarni

