如何为我的 index.html 添加分页?

How do I add pagination to my index.html ?

这是我的代码(它工作正常):

#views.py
class IndexView(generic.ListView):
    template_name = 'index.html'
    context_object_name = 'home_list'
    queryset = Song.objects.all()
    paginate_by = 1
    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['all_artists']=Artist.objects.all()
        context['all_songs']=Song.objects.all()
        context['all_albums']=Album.objects.all()  
        return context

base.html(由index.html扩展):

#base.html
{% block content %}{% endblock %}
{% block pagination %}
          {% if is_paginated %}
            <div class="pagination">
              <span class="page-links">
                {% if page_obj.has_previous %}
                  <a href="{{ request.path }}?page={{ page_obj.previous_page_number}}">Previous</a>
                {% endif %}
                <span class="page-current">
                  Page {{page_obj.number}} of {{page_obj.paginator.num_pages }}
                </span>
                {% if page_obj.has_next %}
                  <a href="{{ request.path }}?page={{page_obj.next_page_number}}">Next</a>
                {% endif %}
              </span>
            </div>
          {% endif %}
          {% endblock %}

还有我的index.html:

{% extends 'base_generic.html' %}
{% block title %}<title>Listen to songs </title>{% endblock %}
{% block content %} 
<h3>Best Songs</h3>

{% for song in all_songs %}
<ol>
    <li><a href="{% url 'music:song_detail' song.id %}">{{song.song_title}}</a> <img src="{{song.song_logo}}" heigt=112, width=114/> <br></li>

</ol>
{% endfor %}
<h3>Best Albums</h3>
{% for album in all_albums %}
<ul>
  <li  title="{{album.album_title}}">
    <img id="img_{{album.id}}" src="{{album.album_logo}}" heigt=112, width=114 />
    <p><a href="{% url 'music:album_detail' album.id %}">{{album.album_title}}</a></p>

  </li>

</ul>
{% endfor %}


{% endblock %}

所以当我编译这个时,我得到了这个window: Image here 但在所有页面中,它仍然是 same.What 我想要的是为每个 page.Help 人显示 1 首歌曲!!!! :] :] :]

看这里:https://www.youtube.com/watch?v=q-Pw7Le30qQ

该视频解释了分页。

选择:https://docs.djangoproject.com/en/1.10/topics/pagination/

如果您只想显示一首歌曲,始终可以选择使用 DetailView,它只会显示一个项目。

这是一个 Whosebug 问题,描述了基于 class 的视图的过程:How do I use pagination with Django class based generic ListViews?

在您的示例中:您不必设置查询集。删除 queryset = ### 并添加 model = #YOURMODELNAME#.

如果你想覆盖查询集,你应该在 def get_queryset() 中进行,这是 ListView 的一个函数。像这样:

class SongView(ListView):
    model = Song
    template_name = 'template_name'

    def get_queryset():
        queryset = super(SongView, self).get_queryset(**kwargs)
        queryset = #aditional filters, ordering, whatever#
        return queryset

您从不使用分页对象,而是创建了一个名为 all_songs 的单独上下文变量。

只需使用正确的上下文数据

{% for song in all_songs %}

应该是

{% for song in home_list %}

您可能也想为其他查询集应用分页,尽管对多个列表进行分页可能会让人感到困惑