首页 > 解决方案 > 当我添加href链接时,帖子中的NoReverseMatch

问题描述

我正在建立一个“游戏”网站,提供线索,个人会做出猜测。

我添加了 home.html、new_game.html、game_detail.html、base.html,现在又添加了 edit_game.html。一切正常,可以创建一个新的列表(在 home.html 中)并显示详细信息。现在我在edit_game.html中添加了编辑游戏的功能。

当我在 game_detail.html 中添加 html 链接“编辑游戏”时,单击列表中的任何游戏时都会出现错误(如下),该列表应显示 game_detail 页面。换句话说,它不会显示 game_detail.html。这是错误:

NoReverseMatch at /post/2/
Reverse for 'edit_game' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/edit/$']

它显然是通过帖子的ID。但它没有选择“/edit/”。这是详细页面代码:

<!-- templates/game_detail.html -->
{% extends 'base.html' %}

{% block content %}
    <div class="post-entry">
        <h2>{{object.title}}</h2>
        <p>{{ object.body }}</p>
    </div>
<a href="{% url 'edit_game' post.pk %}">Edit Game</a>
{% endblock content %}

这是网址代码:

from django.urls import path
from .views import (
    GameListView,
    GameDetailView,
    GameCreateView,
    GameUpdateView,
 )

urlpatterns = [
    path('post/<int:pk>/edit/', GameUpdateView.as_view(), name='edit_game'),
    path('post/<int:pk>/', GameDetailView.as_view(), name='game_detail'),
    path('post/new/', GameCreateView.as_view(), name='new_game'),
    path('', GameListView.as_view(), name='home'),
]

视图代码:

from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView
from .models import Game

class GameListView(ListView):
    model = Game
    template_name = 'home.html'

class GameDetailView(DetailView):
    model = Game
    template_name = 'game_detail.html'

class GameCreateView(CreateView):
    model = Game
    template_name = 'new_game.html'
    fields = ['title', 'author', 'body']

class GameUpdateView(UpdateView):
    model = Game
    template_name = 'edit_game.html'
    fields = ['title', 'body']

标签: python-3.xdjangoexceptiondjango-viewsdjango-templates

解决方案


该对象作为模板传递给模板objectgame因此您可以使用以下方式构造链接:

{% url 'edit_game' game.pk %}

或者:

{% url 'edit_game' object.pk %}

推荐阅读