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

Django访问/topics路径返回404 Not Found错误求助

错误原因

访问/topics路径返回404是路由配置错误直接导致的,代码里一共存在3处问题:

  • 子路由规则缺失+冲突:learning_logs/urls.py里index和topics两个视图绑定的正则都是r'^$',这个规则仅匹配空路径(也就是网站根地址/),完全没有配置能匹配/topics路径的规则,请求进入路由列表后找不到对应映射,直接返回404。同时两个视图绑定同一路由,会导致topics视图永远无法被路由命中。
  • 应用命名空间不一致:根路由learning_log/urls.py中引入子路由时指定的namespace为learning_logs,但子应用内定义的app_name为learning_log,二者不匹配会导致后续模板、视图中做路由反向解析时抛出异常。
  • 视图上下文笔误:topics视图中查询到了主题集合,但传入模板的上下文字段键写为了单数topic,和模板中预期的复数topics变量名不匹配,即使路由通了,页面渲染也会出错。
修复步骤

1. 修正子应用路由配置(learning_logs/urls.py)

给topics页面配置正确的路径匹配规则,同时修正命名空间:

"""Defines URL patterns for Learning_logs."""
from django.urls import re_path as url
from learning_logs import views

app_name = 'learning_logs'  # 和根路由指定的namespace保持一致
    
urlpatterns = [
    # 首页
    url(r'^$', views.index, name='index'),
    # 主题列表页,匹配/topics/路径
    url(r'^topics/$', views.topics, name='topics'),
]

Django默认开启APPEND_SLASH配置,访问不带尾斜杠的/topics时会自动重定向到带斜杠的/topics/,不需要额外写两条规则。

2. 修正视图上下文变量名(learning_logs/views.py)

把传入模板的键名改为和语义一致的topics,和模板中的变量名对齐:

from django.shortcuts import render
from learning_logs.models import Topic

def index(request):
    """Learning Log 首页"""
    return render(request, 'learning_logs/index.html')

def topics(request):
    """展示所有主题"""
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)

3. 验证效果

保存修改后重启Django开发服务器,再次访问http://localhost:8000/topics即可正常加载主题列表页面。


内容的提问来源于stack exchange,提问作者soda.city

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 23:15:51