Django 1.11中登录登出URL配置反向匹配失败问题求助
Ah, I spot the issue right away! When you migrated from Django 1.8's function-based authentication views to Django 1.11's class-based ones, you forgot to include the name parameter in your URL patterns—and that's exactly what Django uses to resolve {% url "login" %} in your templates and settings like LOGIN_URL.
The Root Cause
In your original Django 1.8 code, each URL pattern had a name attribute that acted as a unique identifier for reverse lookups:
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
But in your updated code, those critical name attributes are missing:
url(r'^login/$', auth_views.LoginView.as_view(template_name='registration/login.html')),
Without name='login', Django can't map the string "login" to any URL pattern, hence the "no reverse match" error.
The Fix
Add back the name attributes to each of your auth URL patterns, just like you had in the old code. Here's the corrected URLconf:
from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views url(r'^login/$', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'), url(r'^logout-then-login/$', auth_views.LogoutThenLogin.as_view(template_name='logout_then_login.html'), name='logout_then_login'),
Quick Additional Checks
- Double-check your template paths: you mentioned original templates were in
template/account, but your new code usesregistration/login.html. If your templates are still inaccount, update thetemplate_nameparameter to match (e.g.,template_name='account/login.html'). - Your
settings.pyusesreverse_lazy('login')forLOGIN_URL—once you addname='login'to the URL pattern, this will also work correctly.
That should resolve the reverse matching error completely!
内容的提问来源于stack exchange,提问作者Ian Waring

