Django无限滚动一次浏览所有页面而不实际加载它们

时间:2017-07-06 15:43:57

标签: python django infinite-scroll jquery-waypoints

我正在使用this优秀教程为我的Django应用实现无限滚动。

我希望该应用加载9篇文章,然后显示“loading ...”符号并加载9篇文章。

但是,当用户点击底部时,它会显示加载标志并且没有任何反应。在终端上,我可以看到它“GET”一次请求所有页面:

  

[06 / Jul / 2017 18:22:26]“GET /?page = 2 HTTP / 1.1”200 19124 [06 / Jul / 2017   18:22:27]“GET /?page = 3 HTTP / 1.1”200 18774 [06 / Jul / 2017 18:22:27]   “GET /?page = 4 HTTP / 1.1”200 18772 [06 / Jul / 2017 18:22:28]“GET /?page = 5   HTTP / 1.1“200 19031 [06 / Jul / 2017 18:22:28]”GET /?page = 6 HTTP / 1.1“200   18965 [06 / Jul / 2017 18:22:28]“GET /?page = 7 HTTP / 1.1”200 18676   [06 / Jul / 2017 18:22:28]“GET /?page = 8 HTTP / 1.1”200 18866 [06 / Jul / 2017   18:22:28]“GET /?page = 9 HTTP / 1.1”200 19094 [06 / Jul / 2017 18:22:28]   “GET /?page = 10 HTTP / 1.1”200 18750

这是视图中的代码:

def context_generator(request, title, category):
    """made this function because views are very similar"""
    context_dict={}

    if(category == "index"):
        articles_list = Article.objects.order_by('-pub_date')
    else:
        articles_list = Article.objects.filter(category=category).order_by('-pub_date')

    page = request.GET.get('page', 1)
    paginator = Paginator(articles_list, 9)

    try:
        articles = paginator.page(page)
    except PageNotAnInteger:
        articles = paginator.page(1)
    except EmptyPage:
        articles = paginator.page(paginator.articles_list)

    context_dict['articles'] =  articles
    context_dict['title'] = title

    return context_dict

def index(request):
    return render(request, 'app_name/index.html', context_generator(request, "page title", "index"))

这是index.html:

{% block body_block %}

    <div class="container infinite-container">

         {% for article in articles %}
          <!-- render articles -->
         {% endfor %}

    </div>


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


    <div class="loading" style="display: none;">
      Loading...
    </div>

{% endblock %}

此脚本位于base.html:

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

这些导入位于base.html标题中:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="{% static 'js/jquery.waypoints.min.js' %}"></script>
<script src="{% static 'js/infinite.min.js' %}"></script>

1 个答案:

答案 0 :(得分:1)

这是因为我忘了将这个课程添加到每个文章div:

infinite-item

所以它必须是这样的:

<div class="container infinite-container">

     {% for article in articles %}
          <div class="article col-md-4 col-lg-4 col-xs-12 infinite-item"></div>

     {% endfor %}