Search code examples
pythondjangodjango-urlsdjango-url-reverse

Error with reverse function in django. Can't match a pattern


I am creating my first website using Django. While creating a form and returning the website to the details page of the just created page I came with this NoReverseMatch problem at /books/books/add/ Reverse for 'detail' with keyword arguments '{'pk': 39}' not found. 1 pattern(s) tried: ['books/(?P[0-9]+)/$ I have tried fixing my URL in my urls.py file but being new to this I couldn't get it working.

  urls.py file
from django.conf.urls import url
from django.contrib import admin
from . import views

app_name = 'books'
URL patterns = [
    url(r'^books/$', views.index, name='index'),
    url(r'^$', views.index, name='index'),
    url(r'^(?P<book_id>[0-9]+)/$', views.detail, name='detail'),
    url(r'books/add/$',views.BookCreate.as_view(),name='book-add'),
]


model.py file 
from django.db import models

# Create your models here.
from django.core.urlresolvers import reverse


class Books(models.Model):

    def get_absolute_url(self):
        return reverse('books:detail', kwargs={"pk":self.pk})

    def __str__(self):
        return self.name + '-' + self.author

    name = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    price = models.CharField(max_length=100)
    book_image = models.CharField(max_length=1000)

Solution

  • Change this method from:

    def get_absolute_url(self):
        return reverse('books:detail', kwargs={"pk":self.pk})
    

    To:

    def get_absolute_url(self):
        return reverse('books:detail', kwargs={"book_id":self.pk})

    Because you are using <book_id> in urls, not pk.