Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoReverseMatch django - not a valid view function or pattern

Tags:

python

django

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)])
like image 249
Mark Filley Avatar asked May 08 '26 07:05

Mark Filley


1 Answers

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'),
like image 141
zaidfazil Avatar answered May 10 '26 19:05

zaidfazil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!