Django-Filter not working with Pagination Getting object of type 'PostsFilter' has no len()

I'm trying to make Django-Filter work with Pagination--but it only works when I pass the 'posts' to Paginator--but when I try to pass the f--I get an error >>> object of type 'PostsFilter' has no len()

Other than that everything works fine.

Any suggestions on a workaround? Please see my views.py.

views.py


def posts(request):
    posts = Post.objects.all()

    f = PostsFilter(request.GET, queryset=Post.objects.all())

    paginator = Paginator(posts, 50)

    page_number = request.GET.get("page")
    posts_qs = paginator.get_page(page_number)
    
    return render(request, 'posts/posts.html', {
            'posts':posts_qs,
            'filter':f,
            'title':'Posts'

        })


You are not really filtering the data, since you construct a filter, and then do nothing with it, except passing it to the template. You should first pass it through the filter, and then paginate the post_filter.qs. You then enumerate over the .object_list of the page, so:

def posts(request):
    posts = Post.objects.all()
    post_filter = PostsFilter(request.GET, queryset=posts)
    paginator = Paginator(post_filter.qs, 50)
    page_number = request.GET.get('page')
    posts_qs = paginator.get_page(page_number)
    return render(
        request,
        'posts/posts.html',
        {'posts': posts_qs.object_list, 'filter': post_filter, 'title': 'Posts'},
    )

That being said, I would strongly advise not to do pagination in a function-based view (FBV). We can work with a ListView [Django-doc] making the process easier.

Вернуться на верх