【问题标题】:django basic search function saying NoReverseMatchdjango基本搜索功能说NoReverseMatch
【发布时间】:2026-01-21 22:55:01
【问题描述】:

我正在尝试按照本教程制作一个 todoapp,如果我在 /todoapp/ 处搜索它的内容 NoReverseMatch 并且找不到“搜索”的反向。 “搜索”不是有效的视图函数或模式名称。

这是我的意见.py

def searchtodolist(request):
    if request.method == 'GET':
        query = request.GET.get('content', None)
        if query:
            results = Todoitem.objects.filter(content__contains=query)
            return render(request, 'todoapp.html', {"results": results})
    return render(request, 'todoapp.html')

这是 urls.py

urlpatterns = [
    # path('url path, views.py function names)
    # ex. 127.0.0.1:8000/admin/
    path('addTodo/', addTodo),
    path('admin/', admin.site.urls),
    path('deleteTodo/<int:todo_id>/', deleteTodo),
    path('search/', searchtodolist),
]

最后是我的 todoapp.html

<body>
<br>
<form action="{% url 'search' %}" method="get">{%csrf_token%}
<input type="text" name="content" placeholder="Search a todolist" class="form-control">
<input type="submit" name="submit" value="Search"/>
</form>
<table>
<tr>
    <th colspan="2">List of Todos</th>
</tr>
{% for result in results %}
<tr>
    <td>{{result.content}}</td>
    <td><form action="/deleteTodo/{{todo_items.id}}/" style="display: inline; " method="post"> 
{%csrf_token%}
    <input class="button button1" type="submit" value="Delete"/>
    </form></td>
</tr>
{% endfor %}
</tr>
</table>
</body>

【问题讨论】:

  • 你在 urls.py 中声明了 app_name 吗?
  • 什么意思?对不起,我几个小时前才开始做 django
  • 它的工作但是我使用这个方法
    而不是

标签: django django-views django-templates


【解决方案1】:

你应该给 url 一个名字,以便能够用它的名字来反转它

所以用

    path('search/', searchtodolist, name="search")

这为您的 /search/ 网址提供了一个名为“搜索”的名称。然后您可以通过{% url 'search' %}访问此网址

请注意,如果您在 urls.py 中声明了 app_name,则应在 url 地址名称中指定它

假设 urls.py 之类的:

app_name = "test_app"
urlpatterns = [
    ...
]

那么你应该使用{% url 'test_app:search' %}

【讨论】: