python-3.x - 当我添加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']
解决方案
该对象作为模板传递给模板object
,game
因此您可以使用以下方式构造链接:
{% url 'edit_game' game.pk %}
或者:
{% url 'edit_game' object.pk %}
推荐阅读
- php - 如何进行 cron 作业以从 PHP Smarty Index.tpl 保存到 Index.html?
- python - 有什么方法可以使用 Xlib Python 将 google colab display 连接到我们的系统?
- python-3.x - 结合不同的seaborn分布图
- azure - 拒绝:在 Azure DevOps 管道中检索权限失败
- python - 即使条件为假,While 循环仍在运行
- javascript - 添加新路由时出错,路由配置中需要路径
- angular - 将 .next() 与 takeUntil 一起使用时的参数
- javascript - Javascript属性一旦改变就不会改变
- angular - 如何查看是否有兄弟投影内容?
- selenium - WebDriverWait.until.expected_conditions.presence_of_element_located 不等待重新加载 DOM