CS50W项目1 Wiki:Django路径获取条目页面报错及大小写匹配问题
CS50W Wiki项目条目页面问题解决方案
问题分析
当前存在三个核心问题:
- URL路径不匹配:目标是通过
/wiki/title访问条目,但现有路由直接匹配/title,导致/css/这类路径无法匹配路由规则 - 大小写敏感:只有输入与条目文件名完全大小写一致的标题(如
CSS)才能正常加载,小写css会返回404 - 部分条目(如django、html)返回自定义404,本质也是大小写或路径匹配逻辑问题
解决方案
1. 修正URL路由结构
要实现/wiki/title的访问路径,调整encyclopedia层的路由配置:
wiki/urls.py(保持原有配置)
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include("encyclopedia.urls")) ]
encyclopedia/urls.py(添加wiki前缀)
from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), # 新增wiki前缀,匹配/wiki/title格式的URL path("wiki/<str:title>", views.entry, name="page"), ]
修改后访问http://localhost:8000/wiki/css/即可正确匹配entry视图。
2. 实现不区分大小写的条目查找
CS50W提供的util.get_entry函数是大小写敏感的,修改entry视图逻辑,实现大小写无关的查找:
encyclopedia/views.py
def entry(request, title): """ 不区分大小写查找条目,找到后用正确的大小写获取内容 """ # 获取所有条目名称 all_entries = util.list_entries() matched_title = None # 遍历条目,不区分大小写匹配 for entry in all_entries: if entry.lower() == title.lower(): matched_title = entry break if matched_title is None: return render(request, "encyclopedia/404.html") else: content = util.get_entry(matched_title) html_content = markdown2.markdown(content) return render(request, "encyclopedia/entry.html", { "title": matched_title, "content": html_content })
这段代码会先找到与输入标题大小写无关匹配的条目,再用正确的文件名格式调用get_entry,解决大小写敏感问题。
3. 同步编辑链接的路由配置
entry.html中的编辑链接使用了{% url 'edit' title %},需确保edit路由也添加wiki/前缀(若未配置):
# 在encyclopedia/urls.py中添加 path("wiki/edit/<str:title>", views.edit_entry, name="edit"),
验证修改
- 访问
http://localhost:8000/wiki/css/,可正常加载CSS条目页面 - 访问
http://localhost:8000/wiki/django/或http://localhost:8000/wiki/Django/,均能加载Django条目 - 任意大小写的标题输入都能正确匹配对应条目
内容的提问来源于stack exchange,提问作者Alfalfa9055
相关产品推荐
相关产品推荐

