Home > Blockchain >  How to paginate in django for filtered datas
How to paginate in django for filtered datas

Time:11-28

views.py

import datetime
from .filters import MyModelFilter
from django.shortcuts import render
import pymysql
from django.http import HttpResponseRedirect
from facligoapp.models import Scrapper
from django.db.models import Q
from django.utils import timezone
import pytz
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
users = ""

def index(request):
    if request.method == "POST":
        from_date = request.POST.get("from_date")
        f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d')
        print(f_date)
        to_date = request.POST.get("to_date")
        t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d')
        print(t_date)
        get_records_by_date = Scrapper.objects.all().filter(Q(start_time__date=f_date)|Q(end_time__date=t_date))
        print(get_records_by_date)
        filtered_dates = MyModelFilter(request.GET,queryset=get_records_by_date)
        page = request.GET.get('page', 1)
        paginator = Paginator(filtered_dates.qs, 5)
        global users
        try:
            users = paginator.get_page(page)
        except PageNotAnInteger:
            users = paginator.page(1)
        except EmptyPage:
            users = paginator.page(paginator.num_pages)

    else:
        roles =  Scrapper.objects.all()
        page = request.GET.get('page', 1)
        paginator = Paginator(roles, 5)
        try:
            users = paginator.page(page)
        except PageNotAnInteger:
            users = paginator.page(1)
        except EmptyPage:
            users = paginator.page(paginator.num_pages)

        return render(request, "home.html", {"users": users})

    return render(request, "home.html", {"users": users})

filters.py:

import django_filters
from.models import Scrapper
class MyModelFilter(django_filters.FilterSet):
    class Meta:
        model = Scrapper
        # Declare all your model fields by which you will filter
        # your queryset here:
        fields = ['start_time', 'end_time']

home.html

<!DOCTYPE html>
<html>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
  <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>

<body>
<style>
  h2 {text-align: center;}
</style>
<h1>Facilgo Completed Jobs</h1>
<form action="" method="post">
  {% csrf_token %}
  <label for="from_date">From Date:</label>
  <input type="date" id="from_date" name="from_date">
   <label for="to_date">To Date:</label>
  <input type="date" id="to_date" name="to_date">
  <input type="submit"><br>
</form>
<div >
 <div >
  <div >
    <h2>Summary Details</h2>
    <table id="bootstrapdatatable"  width="100%">
    <thead>
    <tr>
      <th>scrapper_id</th>
      <th>scrapper_jobs_log_id</th>
      <th>external_job_source_id</th>
      <th>start_time</th>
      <th>end_time</th>
      <th>scrapper_status</th>

      <th>processed_records</th>
      <th>new_records</th>

      <th>skipped_records</th>
      <th>error_records</th>
    </tr>
    </thead>
    <tbody>
    {% for stud in users %}
    {% csrf_token %}
      <tr>
        <td>{{stud.scrapper_id}}</td>
        <td>{{stud.scrapper_jobs_log_id}}</td>
        <td>{{stud.external_job_source_id}}</td>
        <td>{{stud.start_time}}</td>
        <td>{{stud.end_time}}</td>
        <td>{{stud.scrapper_status}}</td>
        <td>{{stud.processed_records}}</td>
        <td>{{stud.new_records}}</td>
        <td>{{stud.skipped_records}}</td>
        <td>{{stud.error_records}}</td>
      </tr>
    {% endfor %}
    </tbody>
  </table>
{% if users.has_other_pages %}
    <ul >
   {% if users.has_previous %}
     <li><a href="?page={{ users.previous_page_number }}">«</a></li>
   {% else %}
     <li ><span>«</span></li>
   {% endif %}
   {% if user.number|add:'-4' > 1 %}
    <li><a href="?page={{ page_obj.number|add:'-5' }}">&hellip;</a></li>
   {% endif %}
   {% for i in users.paginator.page_range %}
     {% if users.number == i %}
    <li ><span>{{ i }} <span >(current)</span></span></li>
    {% elif i > users.number|add:'-5' and i < users.number|add:'5' %}
        <li><a href="?page={{ i }}">{{ i }}</a></li>
     {% endif %}
   {% endfor %}
   {% if users.has_next %}
     <li><a href="?page={{ users.next_page_number }}">»</a></li>
   {% else %}
     <li ><span>»</span></li>
   {% endif %}
    </ul>
  {% endif %}
 </div>
 </div>
</div>
</body>
</html>

I need to get only the datas which I have filtered et_records_by_date = Scrapper.objects.all().filter(Q(start_time__date=f_date)|Q(end_time__date=t_date)) in pagination. But when I click the next page its showing different datas. Is there any solution to get only the datas for the particular query. When I post the datas the of dates the 1st pages is showing the correct details but when I click page 2 its showing the other datas

CodePudding user response:

When you click on 'next page' you're performing a GET request, and not a POST request. Which means it will go into the else block, which has no filtering but just returns all the Scrapper objects.

You're better off including the from_date and to_date in a GET request and not using a POST request.

If you're using a form you can simply set the method:

<form method="GET" action="..." />

CodePudding user response:

Shared method

def paginate(request,obj,total=25):
    paginator = Paginator(obj,total)    
    try:
        page = int(request.GET.get('page', 1))
    except:
        page = 1

    try:
        obj_list = paginator.page(page)
    except(EmptyPage,InvalidPage):
        obj_list = paginator.page(paginator.num_pages)
    return obj_list

View

users = UserInfo.objects.all()
data = {
    'users': paginate(request,users,15),
}
return render(request,self.template_name,data)

HTML

{% include './pagination.html' with obj=users %}

pagination.html file

    {% if obj.paginator.num_pages > 1 %}
        <div >
            <ul >
    
                <li >
                

    {% if obj.has_previous %}
                <a data-page="{{obj.previous_page_number}}" href="?page={{obj.previous_page_number}}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="{% trans 'Previous' %}" tabindex="-1"> &laquo; </a>
                {% else %}
                    <a data-page="0"  href="javascript:void(0);" tabindex="-1">&laquo;</a>
                {% endif %}
            </li>
            
            {% for i in obj.paginator.page_range %}
                {% if obj.number == i %}
                    <li >
                        <a data-page="0"  href="javascript:void(0)">{{ i }}</a>
                    </li>
                {% elif i > obj.number|add:'-5' and i < obj.number|add:'5' %}
                    <li ><a data-page="{{i}}"  href="?page={{i}}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">{{ i }}</a>
                    </li>
                {% endif %}
            {% endfor %}

            <li >
                {% if obj.has_next %}
                    <a data-page="{{ obj.next_page_number }}"  href="?page={{obj.next_page_number}}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" tabindex="-1">&raquo;</a>
                {% else %}
                    <a data-page="0"  href="javascript:void(0);" tabindex="-1">&raquo;</a>
                {% endif %}
            </li>
        </ul>
    </div>
{% endif %}
  • Related