Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

object of type 'function' has no len() in django

I use the Django 4 book to learn Django, but I get errors during pagination

TypeError at /blog/

object of type ‘function’ has no len()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

views.py

from django.shortcuts import render, get_object_or_404
from django.http import Http404
from .models import Post
from django.core.paginator import Paginator

def post_list(request):
    posts = Post.published.all()
    # Pagination with 3 posts per page
    paginator = Paginator(post_list, 3)
    page_number = request.GET.get('page', 1)
    posts = paginator.page(page_number)
    return render(request,'blog/post/list.html',{'posts': posts})

paginations.html file

<div class="pagination">
<span class="step-links">
{% if page.has_previous %}
<a href="?page={{ page.previous_page_number }}">Previous</a>
{% endif %}

  <span class="current">
   <p>Page {{ page.number }} of {{ page.paginator.num_pages }}.</p> 
    </span>
    {% if page.has_next %}
    <a href="?page={{ page.next_page_number }}">Next</a>
    {% endif %}
    </span>
    </div>

>Solution :

You are paginating the view function, not the queryset, you should use posts instead of post_list:

def post_list(request):
    posts = Post.published.all()
    # Pagination with 3 posts per page
    paginator = Paginator(post, 3)
    page_number = request.GET.get('page', 1)
    posts = paginator.page(page_number)
    return render(request, 'blog/post/list.html', {'posts': posts})

in the template, the page object is named posts, so:

<div class="pagination">
  <span class="step-links">
  {% if posts.has_previous %}
    <a href="?page={{ posts.previous_page_number }}">Previous</a>
  {% endif %}
  </span>
  <p>
    <span class="step-links">Page {{ posts.number }} of {{ posts.paginator.num_pages }}.</span>
  </p>
  {% if posts.has_next %}
    <a href="?page={{ posts.next_page_number }}">Next</a>
  {% endif %}
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading