为啥 Django 模板模式匹配错误的视图并导致 NoReverseMatch 错误?
Posted
技术标签:
【中文标题】为啥 Django 模板模式匹配错误的视图并导致 NoReverseMatch 错误?【英文标题】:Why is Django template pattern matching with wrong view and causing a NoReverseMatch error?为什么 Django 模板模式匹配错误的视图并导致 NoReverseMatch 错误? 【发布时间】:2017-10-07 02:32:54 【问题描述】:我遇到了 NoReverseMatch 错误。它显示的模式不是它应该与之关联的模式。 错误:
NoReverseMatch at /games/list/
Reverse for 'game_single' with keyword arguments ''pk': ''' not found. 1 pattern(s) tried: ['games/(?P<pk>\\d+)/$']
当视图应该是“game_list”时,我不明白为什么它试图反转“game_single”
我的主要 urls.py:
从 django.conf.urls 导入包含,url 从 django.contrib 导入管理员
from django.conf.urls import include, url
从 django.contrib 导入管理员
urlpatterns = [
#leaving the r'' blank between the parenthesis makes it the
#default URL
url(r'', include('blog.urls')),
url(r'^admin/', admin.site.urls),
url(r'^games/', include('code_games.urls')),
]
我的 code_games 应用程序 urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^list/$', views.game_list, name='game_list'),
url(r'(?P<pk>\d+)/$', views.game_single, name='game_single'),
url(r'^new/$', views.game_new, name='game_new'),
]
我的 code_games 应用程序views.py
#view for seeing all games
def game_list(request):
games = Game.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return render(request, 'code_games/game_list.html', 'games': games)
#view for seeing/playing an individual game
def game_single(request, pk):
games = get_object_or_404(Game, pk=pk)
return render(request, 'code_games/game_single.html', 'games': games)
#view for adding a new game
def game_new(request):
if request.method == "POST":
form = GameForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('game_single', pk=post.pk)
else:
form = GameForm()
return render(request, 'code_games/game_new.html', 'form': form)
我的模板:
% extends 'code_games/base.html' %
% block content %
% for game in games %
<div class="post">
% if game.image != 'Null' %
<a href="% url 'game_single' pk=post.pk %">
<img src="/static/css/images/game.image" style="width:640px;height:228px;">
</a>
% endif %
<div class="date">
game.published_date
</div>
<h1><a href="% url 'game_single' pk=post.pk %"> game.title </a></h1>
<hr>
</div>
% endfor %
% endblock %
我真的不明白为什么 url 试图与 game_single 视图模式匹配,而它应该是 game_list 视图。
【问题讨论】:
【参考方案1】:我一问这个问题就找到了答案……
我必须改变
<a href="% url 'game_single' pk=post.pk %">
到
<a href="% url 'game_single' pk=game.pk %">
和
<a href="% url 'game_single' pk=post.pk %"> game.title </a>
到
<a href="% url 'game_single' pk=game.pk %"> game.title </a>
【讨论】:
以上是关于为啥 Django 模板模式匹配错误的视图并导致 NoReverseMatch 错误?的主要内容,如果未能解决你的问题,请参考以下文章