2👍
✅
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, 'some-template.html', {'book': book})
Note: Models normally have no
…Model
suffix. Therefore it might be better to renametoBookModel
Book
.
Source:stackexchange.com