Django簡單博客實戰(四)--- 分頁實現

Django實現分頁

項目地址:https://github.com/ylpxzx/lifeblog

Django自帶分頁組件實現分頁器

  1. 視圖函數views.py中配置
from django.shortcuts import render,HttpResponse
from django.views.generic import View
from .models import Post
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger # 添加該行
class IndexView(View):
    def get(self,request):
        post_list = Post.objects.all().order_by("-id")
		
        # 分頁器
        paginator = Paginator(post_list,6)
        
		# print("count:",paginator.count)  # 數據總數
        # print("num_pages:",paginator.num_pages) # 總頁數
        # print("page_range:",paginator.page_range) # 頁碼列表
        #
        # page1 = paginator.page(1)  # 第1頁的page對象
        # for i in page1: # 遍歷第1頁的所有數據對象
        #     print(i)
        #
        # print("第一頁的所有數據:",page1.object_list)  # 第1頁的所有數據
        #
        # page2 = paginator.page(2)
        # print(page2.has_next())  # 是否有下一頁
        # print(page2.next_page_number())  # 下一頁的頁碼
        # print(page2.has_previous())  # 是否有上一頁
        # print(page2.previous_page_number())  # 上一頁的頁碼

        page = request.GET.get('page', 1)
        currentPage = int(page)

        try:
            print(page)
            post_list = paginator.page(page)
        except PageNotAnInteger:
            post_list = paginator.page(1)
        except EmptyPage:
            post_list = paginator.page(paginator.num_pages)


        return render(request,"index.html",{'post_list':post_list,"paginator":paginator,"currentPage":currentPage})
  1. 模板文件中編寫分頁語句
{% block area %}
<div class="col-lg-8">
	<div class="blog_left_sidebar">
	{% for post in post_list %}
		<li>{{ post }}</li>
	{% endfor %}
		
		<!-- 分頁欄 -->
		<nav class="blog-pagination justify-content-center d-flex">
			<ul class="pagination">
				{% if post_list.has_previous %}
				<li class="page-item">
					<a href="/index/?page={{ post_list.previous_page_number }}" class="page-link" aria-label="Previous">
						<span aria-hidden="true">
							<span class="lnr lnr-chevron-left"></span>
						</span>
					</a>
				</li>
				{% else %}
				<li class="page-item">
					<a href="#" class="page-link" aria-label="Previous">
						<span aria-hidden="true">
							<span class="lnr lnr-chevron-left"></span>
						</span>
					</a>
				</li>
				{% endif %}

				{% for num in paginator.page_range %}
					{% if num == currentPage %}
						<li class="page-item active"><a href="/index/?page={{ num }}" class="page-link">{{ num }}</a></li>
					{% else %}
						<li class="page-item"><a href="/index/?page={{ num }}" class="page-link">{{ num }}</a></li>
					{% endif %}
				{% endfor %}

				{% if post_list.has_next %}
				<li class="page-item">
					<a href="/index/?page={{ post_list.next_page_number }}" class="page-link" aria-label="Next">
						<span aria-hidden="true">
							<span class="lnr lnr-chevron-right"></span>
						</span>
					</a>
				</li>
				{% else %}
				<li class="page-item">
					<a href="#" class="page-link" aria-label="Next">
						<span aria-hidden="true">
							<span class="lnr lnr-chevron-right"></span>
						</span>
					</a>
				</li>
				{% endif %}
			</ul>
		</nav>
		
	</div>
</div>

{% endblock %}
  1. 如果頁數十分多時,換另外一種顯示方式
class IndexView(View):
    def get(self,request):
        post_list = Post.objects.all().order_by("-id")
        # 分頁器
        paginator = Paginator(post_list,6)
        # print("count:",paginator.count)  # 數據總數
        # print("num_pages:",paginator.num_pages) # 總頁數
        # print("page_range:",paginator.page_range) # 頁碼列表
        #
        # page1 = paginator.page(1)  # 第1頁的page對象
        # for i in page1: # 遍歷第1頁的所有數據對象
        #     print(i)
        #
        # print("第一頁的所有數據:",page1.object_list)  # 第1頁的所有數據
        #
        # page2 = paginator.page(2)
        # print(page2.has_next())  # 是否有下一頁
        # print(page2.next_page_number())  # 下一頁的頁碼
        # print(page2.has_previous())  # 是否有上一頁
        # print(page2.previous_page_number())  # 上一頁的頁碼

        page = request.GET.get('page', 1)
        currentPage = int(page)

        #  如果頁數十分多時,換另外一種顯示方式
        if paginator.num_pages > 11:

            if currentPage - 5 < 1:
                pageRange = range(1, 11)
            elif currentPage + 5 > paginator.num_pages:
                pageRange = range(currentPage - 5, paginator.num_pages + 1)

            else:
                pageRange = range(currentPage - 5, currentPage + 6)

        else:
            pageRange = paginator.page_range

        try:
            print(page)
            post_list = paginator.page(page)
        except PageNotAnInteger:
            post_list = paginator.page(1)
        except EmptyPage:
            post_list = paginator.page(paginator.num_pages)

        return render(request,"index.html",locals())

Django ListView視圖實現分頁

  1. 在視圖views.py文件中配置paginate_by
from django.views.generic.list import ListView
from .models import Post,Category
class IndexView(ListView):
    model = Post
    template_name = "index.html"
    context_object_name = "post_list"
    paginate_by = 6
    def get_queryset(self):
        post_list = Post.objects.all().order_by("-id")
        return post_list

    def get_context_data(self, *, object_list=None, **kwargs):
        kwargs['category_list'] = Category.objects.all().order_by('post_category') # 設置分類字段到模板上下文
        content = super(IndexView,self).get_context_data(**kwargs)
		print(content) # 檢查是否有paginate對象
        return content
  1. 模板文件中編寫分頁語句
		<!-- 分頁欄 -->
		<nav class="blog-pagination justify-content-center d-flex">
			<ul class="pagination">
				{% if page_obj.has_previous %}
				<li class="page-item">
					<a href="{% url 'post:index' %}?page={{ page_obj.previous_page_number }}" class="page-link" aria-label="Previous">
						<span aria-hidden="true">
							<span class="lnr lnr-chevron-left"></span>
						</span>
					</a>
				</li>
				{% else %}
				<li class="page-item">
					<a href="#" class="page-link" aria-label="Previous">
						<span aria-hidden="true">
							<span class="lnr lnr-chevron-left"></span>
						</span>
					</a>
				</li>
				{% endif %}

				{% for num in paginator.page_range %}
					{% if num == page_obj.number %}
						<li class="page-item active"><a href="{% url 'post:index' %}?page={{ num }}" class="page-link">{{ num }}</a></li>
					{% else %}
						<li class="page-item"><a href="{% url 'post:index' %}?page={{ num }}" class="page-link">{{ num }}</a></li>
					{% endif %}
				{% endfor %}

				{% if page_obj.has_next %}
				<li class="page-item">
					<a href="{% url 'post:index' %}?page={{ page_obj.next_page_number }}" class="page-link" aria-label="Next">
						<span aria-hidden="true">
							<span class="lnr lnr-chevron-right"></span>
						</span>
					</a>
				</li>
				{% else %}
				<li class="page-item">
					<a href="#" class="page-link" aria-label="Next">
						<span aria-hidden="true">
							<span class="lnr lnr-chevron-right"></span>
						</span>
					</a>
				</li>
				{% endif %}
			</ul>
		</nav>

	</div>
</div>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章