您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何对基于Django类的通用ListView使用分页?

如何对基于Django类的通用ListView使用分页?

我认为你需要有关将分页与基于新类的视图一起使用的信息,因为使用基于传统函数的视图很容易找到。我发现仅通过设置paginate_by变量就足以激活分页。请参见基于类的通用视图。

例如,在你的views.py

import models
from django.views.generic import ListView

class CarListView(ListView):
    model = models.Car      # shorthand for setting queryset = models.Car.objects.all()
    template_name = 'app/car_list.html'  # optional (the default is app_name/modelNameInLowerCase_list.html; which will look into your templates folder for that path and file)
    context_object_name = "car_list"    #default is object_list as well as model's_verbose_name_list and/or model's_verbose_name_plural_list, if defined in the model's inner Meta class
    paginate_by = 10  #and that's it !!

在你的模板(car_list.html),你可以包括这样的分页部分(我们有一些情境变量可用:is_paginatedpage_obj,和paginator)。

{# .... **Normal content list, maybe a table** .... #}
{% if car_list %}
    <table id="cars">
        {% for car in car_list %}
            <tr>
                <td>{{ car.model }}</td>
                <td>{{ car.year }}</td>
                <td><a href="/car/{{ car.id }}/" class="see_detail">detail</a></td>
            </tr>
        {% endfor %}
    </table>
    {# .... **Now the pagination section** .... #}
    {% if is_paginated %}
        <div class="pagination">
            <span class="page-links">
                {% if page_obj.has_prevIoUs %}
                    <a href="/cars?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="/cars?page={{ page_obj.next_page_number }}">next</a>
                {% endif %}
            </span>
        </div>
    {% endif %}
{% else %}
    <h3>My Cars</h3>
    <p>No cars found!!! :(</p>
{% endif %}
{# .... **More content, footer, etc.** .... #}

显示页面由GET参数指示,只需将?page=nURL 添加到即可。

Go 2022/1/1 18:22:02 有329人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶