对 'detail' 进行反转,但未找到参数 '('',)'。尝试了 1 种模式:['todos\/detail\/(?P<id>[0-9]+)\/$']

Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['todos\\/detail\\/(?P<id>[0-9]+)\\/$']

我正在尝试在 Django 中构建一个待办事项应用程序。 link 无法 link 到详细页面时出现问题。 这是我的代码。

**todos/index.html:**
 {% if todo %}

    <ul>

    {% for todos in todo %}
    <li><a href="{% url 'todos:detail' todo.id %}">{{ todos.text }}</a></li>

    {% endfor %}
    </ul>
{% else %}
    <p>No Todo list are available.</p>
{% endif %}


view.py:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Todo
# Create your views here.


def index(request):
    todo =Todo.objects.all()
    context={'todo':todo}
    return render(request, 'todos/index.html',context)

def detail(request,id):
    todo =Todo.objects.get(id=id)
    context={'todo':todo}
    return render(request, 'todos/detail.html',context)


  todos/url.py:
app_name ="todos"

urlpatterns = [
    path('', views.index, name='index'),
    path('detail/<int:id>/', views.detail, name='detail'),
]

**我必须实际点击才能激活 link:

  • {{ todos.text }}
  • .

    它有效,但没有带我到详细信息页面**

    您将 id 用于错误的变量。所以像下面这样更新代码(我使用 empty 标签来处理空的 todos):

    <ul>
        {% for todos in todo %}
        <li><a href="{% url 'todos:detail' todos.id %}">{{ todos.text }}</a></li>  // Changed here from todo.id to todos.id
        {% empty %}
        <li> No ToDos </li>
        {% endfor %}
    </ul>