Home > Back-end >  NoReverseMatch at post when I add href link
NoReverseMatch at post when I add href link

Time:10-11

I am building a "game" website where clues are given and individuals will make guesses.

I have added home.html, new_game.html, game_detail.html, base.html, and now edit_game.html. All is working correctly to create a new, list (in home.html), and display details. Now I am adding the function to edit the game in edit_game.html.

When I add the html link `Edit Game in game_detail.html, I get the error (below) when I click on any of the games in the list, which should display the game_detail page. In other words, it will not display the game_detail.html. Here is the error:

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

It is clearly passing the ID of the post. But it is not picking up the "/edit/". Here is the detail page code:

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

Here is the urls code:

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

The Views code:

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']

CodePudding user response:

The object is passed as object and game to the template, you can thus construct the link with:

{% url 'edit_game' game.pk %}

or:

{% url 'edit_game' object.pk %}

CodePudding user response:

Willem,

Just for fun, I have tried this, which works:

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

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

But, I'm new to Django and somewhat new to Python. Is the (lower case) game coming from

class GameUpdateView(UpdateView):
    model = Game

?

  • Related