[Django]-Django – TypeError: object of type 'NoneType' has no len() occurred while doing Pagination

2👍

You overwrite the search parameter in the query string, since you’re not repeating it. There’s a bunch of answers accumulated over time in this question on how to handle that.

This is your mistake to fix:

<a href="?page={{ page_obj.previous_page_number }}">previous</a>

(And the same for the “next” link).

Then everything should work as advertized.

Alternatively, you can make the search parameter part of the URL itself, but that has the side effect of making the search cacheable (which is good or bad depending on your site) and requires javascript to move the input to the url.

To do it purely in Django, you transfer the search results to a RedirectView that does nothing else but validate the search parameter and then redirect to the actual search listing.

Again, there are some side effects to that approach, most notably the effect on the back button.

So I advise you to look into querystring modification at the linked answer and if you want to go a different route, post another question with your preferences.

2👍

Your get_queryset() method returns None. Because instead of passing search in query string your are passing page=2. So, your search your variable is None. If the condition fails get_queryset() returning None.

Put your return queryset.filter(title='no result found') outside the condition.

def get_queryset(self):
    queryset = super().get_queryset()
    search = self.request.GET.get('search')
    if search:
        books_with_title = queryset.filter(title__icontains=search)
        if len(books_with_title) > 0:
            return books_with_title

        books_with_author = queryset.filter(authors__name=search)
        if len(books_with_author) > 0:
            return books_with_author

        books_with_publisher = queryset.filter(publisher__name=search)
        if len(books_with_publisher) > 0:
            return books_with_publisher

    return queryset.filter(title='no result found')

Leave a comment