TypeError: object of type 'NoneType' has no len() occurs when I'm adding a pagination to a list view. This happened when I clicked next button to go to page 2. It should have two more results to show.
I guess it's because the value of search is wiped or the queryset becomes none somehow, when I click next (go to page 2), then it returns none.
book/views:
class SearchResultView(generic.ListView):
template_name = 'book/search.html'
model = Book
context_object_name = 'book_list'
paginate_by = 2
def get_queryset(self):
queryset = super().get_queryset()
search = self.request.GET.get('search')
if search:
return Book.objects.filter(
title__icontains=search
)
book/templates/book.html:
<form class="form-inline my-2 my-lg-0" method="get" action="{% url 'book:search' %}">{% csrf_token %}
<input style="font-size: 12px; width: 200px" class="form-control mr-sm-2" name="search" type="search" placeholder="Book Name" aria-label="Search">
<button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
</form>
book/templates/search.html:
<div id="customContents">
{% block customContents %}
{% if book_list %}
<ul>
{% for book in book_list %}
<li>{{ book.title }}</li>
{% empty %}
{% endfor %}
</ul>
{% if is_paginated %}
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
<a href="?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
</span>
</div>
{% endif %}
{% else %}
<h3> No result found. </h3>
{% endif %}
{% endblock %}
</div>
book/urls:
app_name = 'book'
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('search/', views.SearchResultView.as_view(), name='search'),
path('<slug:slug>/', views.BookDetailView.as_view(), name='detail'),
]
It only works fine like this:
class SearchResultView(generic.ListView):
template_name = 'book/search.html'
model = Book
context_object_name = 'book_list'
paginate_by = 2
queryset = Book.objects.filter(
title__icontains='Python'
)

