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

时间:2018-12-29 15:24:25

标签: javascript python django django-views django-pagination

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

以下是该链接的github代码 https://github.com/sibtc/simple-infinite-scroll

链接显示了如何向function based viewsclass based views都添加无限滚动。我已经将此添加到基于函数的视图中,并且效果很好。

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

我的观看次数:

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:(我在FBV的JS文件夹中有以下文件)

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

1 个答案:

答案 0 :(得分:0)

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

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