Django报错:NoReverseMatch: Reverse for 'xxx' not found . 'xxx' is not a valid view function or pattern

本文解决了一个在Django项目中遇到的问题,即在试图反解析URL时找不到新话题视图函数,原因在于urls.py文件中的命名空间错误地多加了一个's'。

最近在学习Django,跟着做一个Django论坛从搭建到部署,教程链接也贴上:【第一部分-django论坛从搭建到部署】一个完整Django入门指南-苍云横渡,做到第三部分时候遇到一个问题,困扰了我很久。经查阅后仍是无果,官方文档也看了依然没有解决问题,后来突然发现了问题,再看看报错的情况,确实就是自己写的时候写错了。先把错误情况贴上:

Internal Server Error: /boards/1/Traceback (most recent call last): File "D:\IDE\Python\Anaconda\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\IDE\Python\Anaconda\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\IDE\Python\Anaconda\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\IDE\pycharm\PyCharm Community Edition 2018.1.2\DjangoProjects\myproject\boards\views.py", line 33, in board_topics return render(request, 'topics.html', {'board': board}) File "D:\IDE\Python\Anaconda\lib\site-packages\django\shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "D:\IDE\Python\Anaconda\lib\site-packages\django\template\defaulttags.py", line 442, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "D:\IDE\Python\Anaconda\lib\site-packages\django\urls\base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "D:\IDE\Python\Anaconda\lib\site-packages\django\urls\resolvers.py", line 622, in _reverse_with_prefix raise NoReverseMatch(msg)django.urls.exceptions.NoReverseMatch: Reverse for 'new_topic' not found. 'new_topic' is not a valid view function or pattern name.[24/Nov/2018 22:54:00] "GET /boards/1/ HTTP/1.1" 500 169427

看起来有点乱,其实关键信息就是最后一句话:

Reverse for 'new_topic' not found . 'new_topic' is not a valid view function or pattern name. 

意思就是new_topic在反析的时候没有被找到,'new_topic' 不是一个有效的视图方法或者模式名。

浏览器报的错也贴上:

urls.py:

view.py:

我注意到其实是urls.py文件中命名空间写错了:

实际上我在view.py文件中定义的方法是new_topic,HTML模板命名也是new_topic.html,所以多加了一个s导致了错误。以后还是需要更加细心。

<think> 我们正在解决的是 `django.urls.exceptions.NoReverseMatch: Reverse for 'test' not found. 'test' is not a valid view function or pattern name.` 错误。 根据引用内容,我们可以总结出以下常见原因和解决方案: 原因1:URL名称拼写错误或未定义 - 检查urls.py中是否定义了name='test'的URL模式 原因2:未正确使用命名空间 - 如果使用了命名空间,则需要使用`app_name:url_name`格式 原因3:视图函数未正确导入或注册 - 确保视图函数在urls.py中正确关联 原因4:URL配置未加载 - 确保包含该URL配置的模块被正确包含到项目URL配置中 原因5:URL反向解析时传递参数错误 - 检查是否需要传递参数,以及参数类型是否正确 具体解决步骤: 步骤1:验证URL配置 - 在项目的urls.py和应用的urls.py中查找名为'test'的URL模式 步骤2:检查命名空间 - 如果使用了命名空间,在模板或代码中应使用`{% url 'namespace:test' %}` 步骤3:检查视图函数存在性 - 确认视图函数存在且名称正确 步骤4:调试URL模式 - 在shell中运行`python manage.py show_urls`查看所有注册的URL 步骤5:检查URL包含层级 - 确保应用的urls.py被包含在项目urls.py中,且命名空间设置正确 步骤6:检查参数传递 - 如果URL需要参数,在反向解析时必须传递 引用[3]中提到了一个具体的例子:在模板中使用`{% url 'news:news_detail' one_hotnews.id %}`时,如果`one_hotnews.id`为空会导致错误。但我们的错误提示中没有参数,所以可能是名称错误或未包含。 因此,我们重点检查名称和包含关系。 示例代码: 正确的urls.py配置: ```python # myapp/urls.py from django.urls import path from . import views app_name = 'myapp' # 如果使用命名空间 urlpatterns = [ path('test/', views.test_view, name='test'), ] ``` 项目urls.py包含应用URL: ```python # project/urls.py from django.urls import include, path urlpatterns = [ path('myapp/', include('myapp.urls')), ] ``` 在模板中使用: ```django <!-- 没有命名空间 --> <a href="{% url 'test' %}">Test</a> <!-- 有命名空间 --> <a href="{% url 'myapp:test' %}">Test</a> ``` 如果以上都正确,那么可能是缓存问题,尝试重启服务器。 另外,注意错误信息中的空格:错误信息显示为 `' test'`,注意名称前面有一个空格?这可能是模板中写错了,比如: 错误写法:`{% url ' test' %}`(多了一个空格) 正确写法:`{% url 'test' %}` 因此,检查模板中url标签内的名称字符串是否有额外的空格。 综上所述,解决方案如下: </think> ### 解决 Django `NoReverseMatch: Reverse for 'test' not found` 错误 这个错误表明 Django 无法找到名为 `'test'` 的 URL 模式。根本原因是 URL 配置与模板/视图中的引用不匹配。以下是系统的解决方案: --- #### 1. **验证 URL 名称是否存在** [核心步骤] 检查项目的 `urls.py` 文件,确认是否定义了 `name='test'` 的 URL 模式: ```python # urls.py (正确配置) from django.urls import path from . import views urlpatterns = [ path('test-page/', views.test_view, name='test'), # ✅ 关键:name='test' ] ``` - 错误信息明确提示 `'test' is not a valid view function or pattern name`[^1] - 确保名称 **完全匹配**(包括大小写和空格) --- #### 2. **检查命名空间冲突** [常见陷阱] 如果使用了应用命名空间,必须使用完整路径: ```python # 项目 urls.py urlpatterns = [ path('app/', include(('myapp.urls', 'myapp'), namespace='myapp')), ] # 模板中正确引用 {% url 'myapp:test' %} <!-- 带命名空间 --> ``` - 错误案例:直接使用 `{% url 'test' %}` 而忽略命名空间会导致解析失败[^3] --- #### 3. **确认视图函数映射** [易忽略点] 验证视图函数是否正确定义并导入: ```python # views.py(视图必须存在) def test_view(request): return HttpResponse("Test Page") # urls.py(正确导入视图) from .views import test_view # 确保导入路径正确 ``` --- #### 4. **检查参数传递** [参数错误] 如需传递参数,必须匹配 URL 模式: ```python # urls.py(带参数的URL) path('detail/<int:pk>/', views.detail, name='detail') # 模板中正确传递参数 {% url 'detail' pk=object.id %} <!-- 参数名必须匹配 --> ``` - 错误案例:`Reverse for 'user-profile' with arguments '('',)' not found` 表明参数传递错误[^2] --- #### 5. **调试工具验证** [快速定位] 使用 Django shell 验证 URL 解析: ```bash python manage.py shell >>> from django.urls import reverse >>> reverse('test') # 如果报错,说明配置错误 '/test-page/' # 成功则返回路径 ``` --- #### 6. **检查包含关系** [层级错误] 确保应用 URL 被正确包含到项目中: ```python # 项目 urls.py(正确包含) urlpatterns = [ path('', include('myapp.urls')), # ✅ 包含应用URL ] ``` --- ### 错误发生机制图解 ```mermaid graph LR A[模板/视图调用 {% url 'test' %}] --> B{URL解析器} B --> C[查找 name='test' 的URL] C -->|存在| D[返回路径 /test-page/] C -->|不存在| E[抛出 NoReverseMatch 错误] subgraph 失败原因 F[名称拼写错误] --> G H[未包含命名空间] --> G I[参数不匹配] --> G G[触发 NoReverseMatch] end ``` --- ### 预防措施 1. **命名规范** - 使用蛇形命名法:`user_profile` 而非 `user-profile`[^2] - 避免保留字冲突 2. **自动化测试** ```python # tests.py from django.test import TestCase from django.urls import reverse class URLTests(TestCase): def test_test_url(self): url = reverse('test') # 验证URL解析 self.assertEqual(url, '/test-page/') ``` 3. **URL 检查工具** ```bash # 列出所有注册URL python manage.py show_urls | grep test ``` --- ### 典型错误案例解析 ```django ❌ 错误模板代码: <a href="{% url ' test ' %}">Test</a> <!-- 名称含多余空格 --> ✅ 修复后: <a href="{% url 'test' %}">Test</a> <!-- 严格匹配名称 --> ``` - 空格会导致解析失败,Django 将 `' test '` 视为独立名称 --- 通过逐步检查 URL 名称、命名空间、参数传递和视图映射,99% 的 `NoReverseMatch` 错误可被解决[^1][^2][^3]。当出现类似 `django_summernote-upload_attachment` 的错误时,同样适用此排查流程[^1]。
评论 13
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值