NoReverseMatch at /allbook Reverse for ‘random_book’ with arguments ‘(”,)’ not found. 1 pattern(s) tried: [‘info/(?P[0-9]+)Z’]
views.py
class MoreInfoView(View):
def get(self, request, id):
book_info = BookModel.objects.filter(id=id).first()
stuff = get_object_or_404(BookModel, id=self.kwargs['id'])
total_likes = stuff.total_likes()
return render(request, 'bookapp/more_info.html', context={
'id': id,
'book_info': book_info,
'book': BookModel,
'total_likes': total_likes,
})
def random_book(self):
book_pks = list(BookModel.objects.values_list('id', flat=True))
pk = random.choice(book_pks)
book = BookModel.objects.get(pk=pk)
return HttpResponse(book)
html
<li class="navigation"><a class="nav-link" href="{% url 'random_book' pk %}">random</a></li>
url.py
urlpatterns = [
path('', index, name='index'),
path('allbook', AllBookView.as_view(), name='allbook'),
path('addbook', AddBookView.as_view(), name='addbook'),
path('register', RegisterView.as_view(), name='reg'),
path('login', LoginView.as_view(), name='login'),
path('logout', LogoutView.as_view(), name='logout'),
path('info/<int:id>', MoreInfoView.as_view(), name='more_info'),
path('profile', profileview, name='profile'),
path('password-change', ChangePasswordView.as_view(), name='change_pass'),
path('like/<int:pk>', LikeView, name='like_book'),
path('info/<int:pk>', views.random_book, name='random_book'),
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Remove the parameter from the random_book:
urlpatterns = [
# …
path('random/', views.random_book, name='random_book')
]
as well as from the {% url … %} template tag:
<a class="nav-link" href="{% url 'random_book' %}">random</a>
You can not return the book itself as object. You should return for example the result of rendering a template:
from django.shortcuts import get_object_or_404, render
def random_book(self):
book_pks = list(BookModel.objects.values_list('pk', flat=True))
pk = random.choice(book_pks)
book = get_object_or_404(BookModel, pk=pk)
return render(request, '<em>some-template.html</em>', {'book': book})
Note: Models normally have no
…Modelsuffix. Therefore it might be better to renametoBookModelBook.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0