我有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 import include,url 来自django.contrib import admin
from django.conf.urls import include, url
来自django.contrib import admin
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 app 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 app 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视图。
答案 0 :(得分: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>