已登录用户访问/login页面未跳转及UnboundLocalError等问题求助
Django页面重定向问题排查与解决
问题1:已登录状态访问/accounts/login未跳转到主页
原因:你访问的/accounts/login是Django auth模块默认提供的登录路由,并未映射到自定义的loginPage视图。自定义视图仅绑定了/login/路径,而默认auth登录视图不会自动在用户已登录时重定向到主页。
解决方法:
- 方案一:将自定义登录视图绑定到
accounts/login路径,修改urls.py:urlpatterns = [ path('accounts/login/', views.loginPage, name='loginPage'), path('logout/', views.logoutUser, name='logoutUser'), path('register/', views.registerPage, name='registerPage'), ] - 方案二:若不需要默认auth登录路由,在项目总urls.py中移除
path('accounts/', include('django.contrib.auth.urls'))配置。
问题2:改路径为accounts/logins后重定向正常,但未登录时触发UnboundLocalError
原因:context变量仅在request.method == 'POST'的代码块内定义,当请求为GET(比如直接访问登录页)时,代码不会进入POST分支,导致context未被定义,返回时触发引用错误。
解决方法:
将context = {}移到函数开头,确保所有请求分支都能获取到该变量:
def loginPage(request): context = {} if request.user.is_authenticated: return redirect("index") if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('index') else: messages.info(request, 'Username OR password is incorrect') return render(request, 'registration/login.html', context)
问题3:删除/login路径后,/accounts/login仍可正常访问
原因:项目总urls.py中大概率引入了Django auth模块的默认路由path('accounts/', include('django.contrib.auth.urls')),该默认路由集合包含/accounts/login/路径,因此即使自定义的/login路径被删除,默认路由依然生效。
解决方法:
- 若不需要默认auth登录视图,直接在总urls.py中删除
include('django.contrib.auth.urls')的相关配置; - 若需保留其他auth路由(如logout)但替换登录视图,可在自定义urls.py中优先定义
accounts/login/路径,覆盖默认路由。
内容的提问来源于stack exchange,提问作者Temka
相关产品推荐
相关产品推荐

