Django 分頁 , 只顯示最近的幾頁( 只顯示靠近的幾頁 )

Django 分頁 , 只顯示最近的頁數( 只顯示靠近的頁數, 最多顯示n頁 )

我不知道怎麼說, 但是這個標題你在搜索引擎搜的時候應該能搜到

其實我前不久看到過更簡單更直接的方法, 但是當時沒做筆記, 然後後面找不到了, 現在很後悔,

我是使用Template的(基本可以實現大部分邏輯)

views.py

    # (ListView)
    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        context_data['max_left_item_count'] = '2'
        return context_data

templates


    {% if is_paginated %}
        <nav aria-label="Page navigation ">
            <ul class="pagination  justify-content-end">
                {% if page_obj.has_previous %}
                    {% if page_obj.number >= max_left_item_count|add:max_left_item_count %}
                        <li  class="page-item"><a class="page-link" href="?page=1">&laquo;&laquo;</a></li>
                    {% endif %}
                    <li  class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li>
                {% endif %}


                {% for i in page_obj.paginator.page_range %}
                    {% if page_obj.number == i %}
                        <li class="page-item active">
                            <span  class="page-link" >{{ i }} <span  class="sr-only page-link">(current)</span></span>
                        </li>
                    {%  elif  page_obj.number|add:max_left_item_count >= i and  i|add:max_left_item_count  >= page_obj.number  %}
                        <li  class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
                    {% endif %}
                {% endfor %}

                {% if page_obj.has_next %}
                    <li  class=" page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}">&raquo;</a></li>
                    {% if  page_obj.paginator.num_pages >  page_obj.number|add:max_left_item_count  %}
                        <li  class=" page-item"><a class="page-link" href="?page={{ page_obj.paginator.num_pages }}">&raquo;&raquo;</a></li>
                    {% endif %}
                {% endif %}


            </ul>
        </nav>
        <span class="float-right">
            {{ page_obj.number }} / {{ page_obj.paginator.num_pages }}
        </span>
    {% endif %} 
    

順便給大家分享一下存儲函數

import hashlib
from django.core.files.storage import FileSystemStorage
class FunFileStorage(FileSystemStorage):
    def _save(self, name, content):
        sha256 = hashlib.sha256()
        for chunk in content.chunks():
            sha256.update(chunk)
        name =  sha256.hexdigest() 

        full_path = super().path(name)
        
        # 這裏大約能給你節約 0.1% 的磁盤空間, 別問我怎麼知道
        if( os.path.exists( full_path )):
            return name

        return super()._save(name, content)
    

settings.py


DEFAULT_FILE_STORAGE = 'xxx.xxx.FunFileStorage'

 

我在唸大學, 一元 五角 一分 都可以, 真心感謝, 謝謝, 謝謝

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