首页 > 解决方案 > 未找到“任务”的反向。“任务”不是有效的视图函数或模式名称

问题描述

在 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'

标签: django

解决方案


请尝试下面的代码,我认为需要 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>

推荐阅读