🔖 Day13 - Paginator, MultiSelectField

2018 - 06 - 26
🔖 Day13 - Paginator, MultiSelectField
之前在index 利用for-loop 顯示出post_list一篇篇的post,但有一個問題沒有解決:分頁。 假如post_list有100個posts,而不想由100~1全都顯示在同一頁,Django很貼心地設有Paginator。 Paginator是在django.core.pagintor.Paginator,有關的內容可以到DjangoProject參考。
1. [Modify view function] 首先到views.py
from django.core.paginator import Paginator
from .models import Post

def index(request):
    post_list = list(reversed(Post.objects.all()))
    p = Paginator(post_list, 10)
    page = request.GET.get('page')
    posts = p.get_page(page)
    return render(request, 'index.html', {'posts':posts})

  • 這裡使用Paginator把post_lost分成每頁10篇,where p is a subclass of Paginator
  • 當網址被GET類request打開時,找尋'page',提取一個由1開始數的頁數。1-based e.g. 1,2,3,4,5,6....
  • 把剛提取的頁數回傳至class method - Paginator.get_page(<number>), return一個page object( 例如Paginator(somelist, 5).page(1) )

2. [Add paginator to template] 到templates把以下HTML內容加入:
<div align='right' class='page'>
{% if posts.has_previous %}
    <a href="?page=1">FIRST</a>
    <a href="?page={{ posts.previous_page_number }}">PREVIOUS</a>
{% endif %}

<span>
    Page {{ posts.number }} of {{ posts.paginator.num_pages }}
</span>

{% if posts.has_next %}
    <a href="?page={{ posts.next_page_number }}">NEXT</a>
    <a href="?page={{ posts.paginator.num_pages }}">LAST</a>
{% endif %}
</div>

上面使用到的parameters包括:
  • posts = Paginator.page,從views.py return的page object
  • posts.has_previous, posts.has_next 是Paginator post object的boolean
  • .number, .previous_page_number, .next_page_number都是page object的methods
  • posts.paginator.num_pages是從page object call返associated Paginator object後,使用Paginator的class methodnum_pages

之前提及過ChoiceField以及SelectDateWidget,是在一堆選項或日子當中選取其中一個。 但假如想一次過勾選好幾個,例如tags,可以使用open source - MultiSelectField。 詳細資料可以到這裡參考。
1. [django-multiselectfield] 打開terminal安裝:
$pipenv install django-multiselectfield
models.py
form multiselectfield import MultiSelectField

class Post(models.Model):
    ...
    tag = MultiSelectField(<max_choices=3>, choices=(
        ('tag1','tag1'),
        ('tag2','tag2'),
        ('tag3','tag3'),
        ('tag4','tag4'),
    ))


Comments

There is no comment yet

New Comment

Please Login to comment