2
votes

I have a NoReverseMatch error. The pattern it is showing is not the one it is supposed to be associated with. The error:

NoReverseMatch at /games/list/
Reverse for 'game_single' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['games/(?P<pk>\\d+)/$']

I dont understand why its trying to Reverse for 'game_single' when the view is supposed to be 'game_list'

My Main urls.py:

from django.conf.urls import include, url from django.contrib import admin

from django.conf.urls import include, url

from 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')),
]

My 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'),
]

My 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})

My Template:

{% 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 %}

I really don't understand why the url is trying to pattern match with the game_single view when it should be the game_list view.

1

1 Answers

1
votes

As soon as I asked this I found the answer....

I had to change

<a href="{% url 'game_single' pk=post.pk %}">

to

<a href="{% url 'game_single' pk=game.pk %}">

and

<a href="{% url 'game_single' pk=post.pk %}">{{ game.title }}</a>

to

<a href="{% url 'game_single' pk=game.pk %}">{{ game.title }}</a>