美文网首页django分页
django自带分页

django自带分页

作者: 赖三石 | 来源:发表于2017-07-18 11:25 被阅读0次

    urls.py

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^index/', views.index, name='index'),
    ]
    

    views.py

    # encoding=utf-8
    from django.shortcuts import render
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    
    def index(request):
    
        #模拟数据,列表生成式
        a_list = [i for i in range(1, 1003)]
    
        paginator = Paginator(a_list, 8)  # Show 25 contacts per page
        page = request.GET.get('page')
        try:
            data = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            data = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            data = paginator.page(paginator.num_pages)
    
        return render(request,'index.html',{
            'data': data
        })
    

    template

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .active{
                background-color: #1b6d85;
            }
            #ss li{
                float: left;
                display: inline;
                margin-left: 10px;
            }
        </style>
    </head>
    <body>
    
    <ul>
        {% for d in data %}
            <li>{{ d }}</li>
        {% endfor %}
    </ul>
    
    {#{% for i in page %}#}
    {#{{ i|safe }}#}
    {#{% endfor %}#}
    <ul id="ss">
    {% if data.has_previous %}
        <li><a href="/index/?page={{ data.previous_page_number }}" >上一页</a></li>
    {% endif %}
    
    {% for p_num in data.paginator.page_range %}
        {% if data.number == p_num %}
            <li><a class="active" href="/index/?page={{ p_num }}">{{ p_num }}</a></li>
        {% else %}
            <li><a href="/index/?page={{ p_num }}">{{ p_num }}</a></li>
        {% endif %}
    {% endfor %}
    
    {% if data.has_next %}
        <li><a href="/index/?page={{ data.next_page_number }}" >下一页</a></li>
    {% endif %}
    </ul>
    </body>
    </html>
    

    相关文章

      网友评论

        本文标题:django自带分页

        本文链接:https://www.haomeiwen.com/subject/dugckxtx.html