当我给列表视图添加分页时,出现了
我猜是因为当我点击“下一页(进入第二页)”时,
搜索表单:
book/views:
TypeError: object of type 'NoneType' has no len()
的错误。这个错误发生在我点击“下一页”按钮进入第二页时。它应该有两个结果要显示。我猜是因为当我点击“下一页(进入第二页)”时,
search
的值被清除或者queryset
变成了空,然后返回了none
。
错误信息:
![enter image description here](https://istack.dev59.com/jJeHh.webp)
![enter image description here](https://istack.dev59.com/OobOV.webp)
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'),
]
只有这样才能正常工作:
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'
)
len()
进行测试,只需简单地执行if books_with_title:
就可以了。 - MD. Khairul Basarsearch
是假的,那么你不返回任何东西。 - Willem Van Onsemif search
语句之外使用return queryset.none()
。因为最初可能不存在search
参数。 - Willem Van Onsem