使用 Django Paginate 重复查询集的 Django 无限滚动

Django Infinite scroll using Django Paginate repeating the queryset

简介: 我正在使用下面的 link 为我的项目添加无限滚动 https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html

下面是 github 代码 link https://github.com/sibtc/simple-infinite-scroll

link 展示了如何为 function based viewsclass based views 添加无限滚动。我已将其添加到我的基于函数的视图中,并且效果很好。

问题: 我的 post-列表中有 8 posts class-based view。添加 paginate_by = 3 后,我只能看到 8 个 post 中的 3 个 post。每次我向下滚动时,这 3 post 都会无限循环地重复

我的观点:

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

我的 Base.html:(我在 JS 文件夹中有以下文件,它们适用于我的 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 %}

我的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 %}

在模板中,我将 post_list 替换为 page_obj,请参见下面的代码。做到了

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