django - 未找到“任务”的反向。“任务”不是有效的视图函数或模式名称
问题描述
在 task_list.html {{task.title}} 中工作正常,但下面几行 href 中的“任务”不起作用。它显示错误“NoReverseMatch at / Reverse for 'task' not found.'task' 不是有效的视图函数或模式名称。” 对于 task_list.html 中第二个表行中的 a 标记
任务列表.html:
<h1>My To Do List</h1>
<table>
<tr>
<th>Item</th>
<th></th>
</tr>
{% for task in tasks %}
<tr>
<td>{{task.title}}</td>
<td><a href="{% url 'task' task.title %}">View</a></td>
</tr>
{% empty %}
<h3> No items in list</h3 >
{% endfor %}
</table>
网址.py:
from django.urls import path
from .views import TaskList, TaskDetail
urlpatterns = [
path('', TaskList.as_view(), name='tasks'),
path('task/<int:pk>', TaskDetail.as_view(), name='tasks'),
]
视图.py:
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Task
class TaskList(ListView):
model = Task
context_object_name = 'tasks'
class TaskDetail(DetailView):
model = Task
context_object_name = 'task'
template_name = 'base/task.html'
解决方案
请尝试下面的代码,我认为需要 pk 但你通过了标题
<h1>My To Do List</h1>
<table>
<tr>
<th>Item</th>
<th></th>
</tr>
{% for task in tasks %}
<tr>
<td>{{task.title}}</td>
<td><a href="{% url 'task' task.pk %}">View</a></td>
</tr>
{% empty %}
<h3> No items in list</h3 >
{% endfor %}
</table>
推荐阅读
- ef-core-3.0 - 如何在 EF Core 3.0 中使用数据库视图?
- ruby - 如何持续观察不断增长的日志文件并解析 ruby 中的更改
- java - 将用户输入的数字转换为单词
- matlab - MATLAB中N个函数句柄的总和
- python-3.x - 结构通过套接字解包可变长度字符串时出错
- html - 当我将其编程为其他方式时,为什么显示属性会恢复为其默认值?
- python - 如何在不使用循环的情况下计算给定矩阵的所有列向量对之间的欧几里得距离?(仅使用 numpy)
- ios - 多个用户项目的应用内自动续订订阅(iOS)
- extjs - 在 ExtJS 4.1 中单击外部窗口时如何关闭窗口?
- unix - Unix grep、sed、awk 命令从日志文件中查找请求的平均响应时间