Example code: Filter & Paginator


views.py


Paginatorクラスには、次の属性があります.
  • page range
    print: range(1, 3)
  • {{ tutorial_page_obj.paginator.page_range}}
  • current page number
  • {{ tutorial_page_obj.number }}
    写真
    from張高+ガイドバーPython Web開発のテンプレート
    from .filters import TutorialFilter
    from django.core.paginator import Paginator, 
    
    def HomeView(request):
    
    #Filter
        context = {}
        filtered_tutorials = TutorialFilter(
            request.GET,
            queryset=Tutorial.objects.all()
        )
        context['filtered_tutorials'] = filtered_tutorials
    
    #Pagination
        paginated_filtered_tutorials = Paginator(filtered_tutorials.qs, 5)
        page_number = request.GET.get('page') 
        tutorial_page_obj = paginated_filtered_tutorials.get_page(page_number)
        
        context['tutorial_page_obj'] = tutorial_page_obj
    
    
    
        return render(request, 'index.html', context=context)

    templates


    1. loading my_url function from hub_extras

    {% load hub_extras %}

    2. filter

        <!--Filter-->
                    <div class="card card-body filter-bar">
    
                      <form method="get">
    
                        <div class="row justify-content-md-center">
    
                        <div class="col-sm-2 form-group is-valid">
                            <label for="id_title__icontains">by Title</label>
                            <input type="text" name="title__icontains" class="form-control is-valid" placeholder="search" title="" id="id_title__icontains">
                        </div>
    
                        <div class="col-sm-2 form-group is-valid">
                            <label for="id_instructor__icontains">by Instructor</label>
                            <input type="text" name="instructor__icontains" class="form-control is-valid" placeholder="search" title="" id="id_instructor__icontains">
                        </div>
    
                        <div class="col-sm-2 form-group is-valid"><label for="id_language">Language</label>
                            <select name="language" class="language form-control is-valid" title="" id="id_language">
                            <option value="" selected> select </option>
                            <option value="Korean">Korean</option>
                            <option value="English">English</option>
                            </select>
                        </div>
    
                        <div class="col-sm-2 form-group is-valid">
                            <label for="id_difficulty"Choose Difficulty> Difficulty </label>
                            <select name="difficulty" class="difficulty form-control is-valid" title="" id="id_difficulty">
                            <option value="" selected >select</option>
                            <option value="Beginner">Beginner</option>
                            <option value="Intermediate">Intermediate</option>
                            <option value="Advanced">Advanced</option>
                            </select>
                        </div>
    
                        <div class="col-sm-2 form-group is-valid">
                            <label for="id_date_sort">Sort by Date </label>
                            <select name="date_sort" class="sortbydate form-control form-control-sm is-valid" placeholder="1234" title="" id="id_date_sort">
                            <option value="" selected> Newest to Oldest </option>
                            <option value="newest">Newest</option>
                            <option value="oldest" >Oldest</option>
                            </select>
                        </div>
    
                          <div class="col-sm-1 form-group is-valid" style="padding-left: 0.2px;">
                            <button class="btn btn-warning btn-md search_btn search_btn filter-btn" type="submit"> Search </button>
                          </div>
    
    
                          <div class="col-sm-1 form-group is-valid">
                          <a class="btn btn-secondary btn-md reset-btn filter-btn" href="{% url 'hub:home'%}" role="button">Reset</a>
                          </div>
    
                        </div>
                      </form>
                    </div>
        <!-- filter -->

    3. table

                   <!-- table -->
                    <main>
                        <div class="container">
    
                          <section class="text-center mb-4">
    
    
                          <div class="container-fluid">
                              <div class="row justify-content-md-center">
    
                                  <div class="card card-body" >
                          <!--count-->
                                      <div class="tutorial-count">
                                         <span class="text-right"> Total: {{ tutorial_page_obj.paginator.count}} </span>
                                      </div>
                           <!--table-->
                                      <table class="table">
                                          <tr>
                                              <th> </th>
                                              <th> Title</th>
                                              <th> Instructor</th>
    
                                              <th> Tags</th>
                                              <th> Last Updated</th>
                                              <th> Difficulty</th>
                                              <th> Language</th>
                                              <th> Duration</th>
                                          </tr>
    
                                          {% for item in tutorial_page_obj %}
                                          <tr>
    
                                              <td><a href="{{ item.get_add_to_curriculum_url }}"
                                                     class="btn btn-primary btn-md my-0 p">Add
                                              </a></td>
    
                                              <td><a href="{% url 'hub:tutorial_detail' item.pk %}">{{item.title}}</a></td>
                                              <td>{{item.instructor}}</td>
                                              <td>
                                                  {% for tag in item.tags.all %}
                                                  {{ tag }}
                                                  {% endfor %}
                                              </td>
                                              <td>{{item.last_updated}}</td>
                                              <td>{{item.difficulty}}</td>
                                              <td>{{item.language}}</td>
                                              <td>{{item.duration}}</td>
                                          </tr>
                                          {% endfor %}
                                      </table>
                                  </div>
                              </div>
                          <!--  contatiner  -->
                          </div><br>
                             </section>
                          </div>
                         </main>
                    <!--table-->

    4. custom templatetag

    from django import template
    
    register = template.Library()
    
    
    
    @register.simple_tag
    def my_url(value, field_name, urlencode=None): #value will pass page number, field_name pass string page and URL
        url = f'?{field_name}={value}'
    
        if urlencode:
            querystring = urlencode.split('&')
            filtered_querystring = filter(lambda p: p.split('=')[0]!=field_name, querystring) #take query string list, take each string and split it by 2, if the first string is equel to the field.
            encoded_querystring = '&'.join(filtered_querystring)
            url = f'{url}&{encoded_querystring}'
    
        return url

    5. pagination


    .has_previous
    .has_next
    .number
    .paginator.page_range
    href url is created in custom template tag
    
    <!--Pagination-->
          <nav class="d-flex justify-content-center">
            <ul class="pagination pg-blue">
    <!--Previous Page-->
      {% if tutorial_page_obj.has_previous %}
              <li class="page-item ">
                <a class="page-link" href="{% my_url tutorial_page_obj.previous_page_number 'page' request.GET.urlencode %}" aria-label="Previous">
                  <span aria-hidden="true">&laquo;</span>
                  <span class="sr-only">Previous</span>
                </a>
              </li>
      {% else %}
              <li class="page-item disabled">
                <a class="page-link" tabindex="-1" aria-disabled="true" href="#">
                  <span aria-hidden="true">&laquo;</span>
                  <span class="sr-only">Previous</span>
                </a>
              </li>
      {% endif %}
    
    
    <!--Page List-->
    
      {% for item in tutorial_page_obj.paginator.page_range %}
        {% if item == tutorial_page_obj.number %}
    
              <li class="page-item active" aria-current="page">
                <a class="page-link" href="{% my_url tutorial_page_obj.number 'page' request.GET.urlencode %}">{{ item }}
                  <span class="sr-only">(current)</span>
                </a>
              </li>
      {% else %}
              <li class="page-item">
                  <a class="page-link" href="{% my_url item 'page' request.GET.urlencode %}">{{ item }}
               </a>
              </li>
      {% endif %}
      {% endfor %}
    
    <!--Next Page-->
    
      {% if tutorial_page_obj.has_next %}
              <li class="page-item">
                <a class="page-link" href="{% my_url tutorial_page_obj.next_page_number 'page' request.GET.urlencode %}" aria-label="Next">
                  <span aria-hidden="true">&raquo;</span>
                  <span class="sr-only">Next</span>
                </a>
              </li>
      {% else %}
              <li class="page-item disabled">
                <a class="page-link" tabindex="-1" aria-disabled="true" href="#">
                  <span aria-hidden="true">&raquo;</span>
                  <span class="sr-only">Next</span>
                </a>
              </li>
      {% endif %}
    </ul>
    </nav>
          <!--Pagination-->