You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中NoReverseMatch错误:找不到'login'反向匹配求助

Django NoReverseMatch: 'login' 路由匹配失败问题排查

问题描述

重复发帖致歉,尽管login相关配置看似正确,但仍报错:

NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name

当前配置

1. settings.py

LOGIN_URL = '/login/'

2. APP/templates/base.html

{% if user.is_authenticated %}
    <a href="{% url 'logout' %}">Logout</a>
{% else %}
    <a href="{% url 'login' %}">Login</a>
{% endif %}

3. APP/views.py

from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required

@login_required(login_url='login') # Redirect to the login page if not authenticated
def protected_intro(request):
    return render(request, 'intro.html')

4. APP/urls.py

from django.urls import path
from django.contrib.auth.views import LoginView
from . import views

app_name = 'APP'

urlpatterns = [
    ...
    path('login/', LoginView.as_view(), name='login'),
]

解决方案

1. 模板中添加路由命名空间

你的APP路由已设置app_name = 'APP',引用命名路由时必须带上命名空间前缀,否则Django无法定位到对应APP的路由。修改base.html:

{% if user.is_authenticated %}
    <a href="{% url 'APP:logout' %}">Logout</a>
{% else %}
    <a href="{% url 'APP:login' %}">Login</a>
{% endif %}

(注意:如果logout路由不在当前APP中,也要对应调整其命名空间)

2. 修正login_required装饰器的路由参数

@login_required(login_url='login')中的login没有指定命名空间,同样会导致路由匹配失败,有两种修正方式:

  • 方式一:添加命名空间
@login_required(login_url='APP:login')
def protected_intro(request):
    return render(request, 'intro.html')
  • 方式二:直接依赖settings中的LOGIN_URL配置,省略login_url参数
@login_required()
def protected_intro(request):
    return render(request, 'intro.html')

3. 确认根路由已包含APP路由

确保项目根目录的urls.py中已引入APP的路由配置,否则APP的路由不会被加载:

from django.urls import include, path

urlpatterns = [
    # ... 其他项目路由
    path('', include('APP.urls')),
]

内容的提问来源于stack exchange,提问作者SNandi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 19:42:44