简体   繁体   中英

Django Infinite scroll using Django Paginate repeating the queryset

Intro: I am using the the below link to add infinite scroll to my project https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html

below is the github code for that link https://github.com/sibtc/simple-infinite-scroll

The link shows how to add infinite scroll to both function based views and class based views . I have added this to my function based view and it works perfect.

The problem: I have 8 posts in my post-list which is a class-based view . After I add paginate_by = 3 I can only see 3 posts of the 8 posts. Everytime I scroll down these 3 posts keep repeating in an infinite loop

My Views:

class Postlist(SelectRelatedMixin, ListView):
    model = Post
    select_related = ('user', 'group')
    paginate_by = 3
    context_object_name = 'post_list'
    template_name = 'posts/post_list.html'

    def get_queryset(self):
         queryset = super(Postlist, self).get_queryset().order_by('-created_at')
         query = self.request.GET.get('q')
         if query:
             queryset = queryset.filter(
             Q(title__icontains=query)|
             Q(user__username__iexact=query)|
             Q(user__first_name__iexact=query)|
            Q(user__last_name__iexact=query)

        )
          return queryset

My Base.html: (I have the below files in JS folder they worked for my FBV)

    <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
    <script src="{% static 'js/jquery.waypoints.min.js' %}"></script>
    <script src="{% static 'js/infinite.min.js' %}"></script>
{% block javascript %}{% endblock %}

My post_list.html:

<div class="col-md-8">
    <div class="infinite-container">
        {% for post in post_list %}
        <div class="infinite-item">
            {% include "posts/_post.html" %} <!---This code is good---->
        </div>
        {% empty %}
               some code    
        {% endfor %}
    </div>
    <div class="loading" style="display: none;">
        Loading...
    </div>

    {% if page_obj.has_next %}
        <a class="infinite-more-link" href="?page={{ post_list.next_page_number }}">More</a>
    {% endif %}

</div>

{% block javascript %}
  <script>
    var infinite = new Waypoint.Infinite({
      element: $('.infinite-container')[0],
      onBeforePageLoad: function () {
        $('.loading').show();
      },
      onAfterPageLoad: function ($items) {
        $('.loading').hide();
      }
    });
  </script>
{% endblock %}

In the templates I replaced post_list with page_obj see below code. That did it

{% if post_list.has_next %}
   <a class="infinite-more-link" href="?page={{page_obj.next_page_number }}">More</a>
{% endif %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM