3

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)])
zaidfazil
  • 9,017
  • 2
  • 24
  • 47
Mark Filley
  • 163
  • 2
  • 2
  • 8

1 Answers1

1

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'),
zaidfazil
  • 9,017
  • 2
  • 24
  • 47
  • 3
    Thanks for the tips. This helped, but did not resolve the issue. I looked closer at the stack and found the call back was trying to access the urls.py in another app. After adding the namespace to the call, it worked `library:book_details` I found some references that helped me out [source1](http://cheng.logdown.com/posts/2016/01/06/django-how-to-reverse-urls-belonged-to-other-apps) [source2](https://stackoverflow.com/questions/26812980/django-template-url-from-another-app) – Mark Filley Jun 28 '17 at 04:26
  • I forgot to mention the namespace buddy, glad you figured it out yourself. Keep up the good work. – zaidfazil Jun 28 '17 at 04:27
  • What I was also missing "namespace". Solved the issue. Thanks ! – Ajay Kedare Sep 10 '17 at 07:34