Home > Software engineering >  NoReverseMatch at /allbook Reverse for 'random_book' with arguments '('',)&
NoReverseMatch at /allbook Reverse for 'random_book' with arguments '('',)&

Time:04-30

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 ><a  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'),

CodePudding user response:

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  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, 'some-template.html', {'book': book})

Note: Models normally have no …Model suffix. Therefore it might be better to rename BookModel to Book.

  • Related