Mark Filley
Mark Filley

Reputation: 173

NoReverseMatch django - not a valid view function or pattern

Currently using Django 1.11. I get an exception of

Reverse for 'book_details' not found. 'book_details' is not a valid view function or pattern name.
Request Method: GET
Request URL:    http://localhost:8000/library/book/c7311ecf-eba7-4e9d-8b1a-8ba4e075245a/
Django Version: 1.11
Exception Type: NoReverseMatch

I want to use the get_absolute_url from my Model in the details page to go to a Update page. When I take out the reference to the .id and use the get_absolute_url. I checked to see the name "book_details" is referenced properly. I can go to the page and have books details render properly. In the admin console of Django, the "view on site" button also does not render properly it shows this localhost:8000/admin/r/13/c7311ecf-eba7-4e9d-8b1a-8ba4e075245a/ so it does not get the library/books either

current <a href =" {{ book.id }}/update">Update</a>

desired <a href =" {{ book.get_absolute_url }}/update">Update</a>

Where have I mistyped for this to not work?


Setup in files:

Yes, I do have UUID as the primary key.

In views.py

class BookDetailsView(generic.DetailView):
"""
Generic class-based detail view for a Book.
"""
model = Book

in urls.py

url(r'^book/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$', views.BookDetailsView.as_view(), name='book_details'),
url(r'^book/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/update/$', views.BookUpdate.as_view(), name='book_update'),

in models.py

class Book(models.Model):

def get_absolute_url(self):
    """Returns the URL of the book for details"""
    return reverse('book_details', args=[str(self.id)])

Upvotes: 3

Views: 11697

Answers (1)

zaidfazil
zaidfazil

Reputation: 9235

Try providing the pk as keyword argument to the reverse function,

def get_absolute_url(self):
    return reverse('book_details', kwargs={ 'pk': str(self.id) })

Also, you are missing a trailing slash at the end of the url,

url(r'^book/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', views.BookDetailsView.as_view(), name='book_details'),

Upvotes: 1

Related Questions