Pagination in django

Pagination in Django

Create pagination file pagination.html

{% if page_obj.paginator.num_pages > 1 %}
<ul class="pagination">
    {% if page_obj.has_previous %}
        <li class="page-item">
            <a class="page-link" href="javascript:void(0)" onclick="search_by_key(1)">&laquo; First</a>
        </li>
        <li class="page-item">
            <a class="page-link" href="javascript:void(0)" onclick="search_by_key({{ page_obj.previous_page_number }})">Previous</a>
        </li>
    {% endif %}

    {% for num in page_obj.paginator.page_range %}
        {% if page_obj.number == num %}
            <li class="page-item active">
                <a class="page-link" href="javascript:void(0)">{{ num }}</a>
            </li>
        {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
            <li class="page-item">
                <a class="page-link" href="javascript:void(0)" onclick="search_by_key({{ num }})">{{ num }}</a>
            </li>
        {% endif %}
    {% endfor %}

    {% if page_obj.has_next %}
        <li class="page-item">
            <a class="page-link" href="javascript:void(0)" onclick="search_by_key({{ page_obj.next_page_number }})">Next</a>
        </li>
        <li class="page-item">
            <a class="page-link" href="javascript:void(0)" onclick="search_by_key({{ page_obj.paginator.num_pages }})">Last &raquo;</a>
        </li>
    {% endif %}
</ul>
{% endif %}

make view file post_view.py

from django.shortcuts import render
from django.http import JsonResponse
from django.db.models import Q
from models.post_model import Post
from serializers.post_serializer import PostSerializer

from django.template.loader import render_to_string

from django.core.paginator import Paginator


def post_list_view(request):
    """Render the post list template"""
    return render(request, 'post/post_list.html', {'post_list': []})


def post_search_api(request):
    """API endpoint for searching posts"""
    search_key = request.GET.get('q', '').strip()
    page_number = request.GET.get('page', 1)
    
    # Start with base queryset
    post_list = Post.objects.all().select_related('sub_category')
    
    # Apply search filter if search key exists
    if search_key:
        post_list = post_list.filter(
            Q(title__icontains=search_key) 
        )


    paginator = Paginator(post_list, 10)  # Show 10 posts per page
    page_obj = paginator.get_page(page_number)

    serializer = PostSerializer(page_obj, many=True)


     # Render HTML table
    html = render_to_string('post/partials/post_table.html', {
        'post_list': serializer.data
    })
    
    # Render pagination
    pagination_html = render_to_string('pagination.html', {
        'page_obj': page_obj
    })

    return JsonResponse({
        'html': html,
        'pagination': pagination_html  # Add pagination HTML here if needed
    })

    # return JsonResponse(serializer.data, safe=False)

make post.html file for frontend

{% extends "layouts/master.html" %}

{% block title %}
    Postsparrow
{% endblock %}

{% block style %}
{% endblock %}

{% block content %}

	<div class="content-wrapper">


        <div class="row">

            <div class="col-lg-12 grid-margin stretch-card">

                <div class="card">

                    <div class="card-body">

                        <h4 class="card-title">

                        <span custom class="">

                            Post details

                        </span>

                        </h4>

                        <p class="card-description">

                     
                        </p>



                        <div class="row">

                            <div class="col-md-6">

                                <a class="btn btn-primary mr-2 btn-sm"

                                   href="javascript:void(0)"

                                   onclick="status_update_all(1,'#">

                                   Active
                                    <i class="mdi mdi-check menu-icon"></i>

                                </a>



                                <a class="btn btn-primary mr-2 btn-sm"

                                   href="javascript:void(0)"



                                   onclick="status_update_all(0,'')">

                                   Inactive

                                    <i class="mdi mdi-block-helper menu-icon"></i>

                                </a>



                            </div>

                            <div class="col-md-3">

                            </div>

                            <div class="col-md-3">

                                <div class="form-group">

                                    <input type="text"

                                           id="search_item"

                                           name="search_item"

                                           placeholder="Search Post"

                                           onkeyup="search_by_key(1)"

                                           class="form-control">

                                </div>



                            </div>

                            <div class="table-responsive">

                                <div id="search_list_box">


                                </div>

                            </div>



                        </div>

                        <div class="mt-4" id="pagination_div">
						    <nav aria-label="Page navigation">
						        <ul class="pagination d-flex justify-content-end" id="pagination"></ul>
						    </nav>
						</div>

                    </div>

                </div>

            </div>

        </div>

    </div>

{% endblock %}


{% block script %}
<script>
 	function search_by_key(page=1) {
	    const search_term = $('#search_item').val();
	    
	    $.ajax({
	        url: "{% url 'postsearchapi' %}",
	        method: 'GET',
	        data: {
	            q: search_term,
	            page: page
	        },
	        success: function(response) {
	            $('#search_list_box').html(response.html);
	            $('#pagination').html(response.pagination);
	        },
	        error: function(xhr) {
	            console.error('Search error:', xhr.responseText);
	        }
	    });
	}

	// Add debounce to prevent rapid firing
	let searchTimer;
	$('#search_item').on('keyup', function() {
	    clearTimeout(searchTimer);
	    searchTimer = setTimeout(() => {
	        search_by_key(1);
	    }, 300);
	});


	// A $( document ).ready() block.
	$( document ).ready(function() {
	    search_by_key(page=1)
	});
</script>
{% endblock %}

make table for post_table.html

<table class="table table-bordered table-hover">
    <thead>
        <tr>
            <th>
                <div class="form-check">
                    <label class="form-check-label">
                        <input name="all_action"
                               class="all_action form-check-input"
                               type="checkbox"
                               onclick="check_action()">
                        <i class="input-helper"></i>
                    </label>
                </div>
            </th>
            <th>Avatar</th>
            <th>Title</th>
            <th>Sub Category</th>
            <th>Category</th>
            <th>Status</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        {% for value in post_list %}
            <tr>
                <td>
                    <div class="form-check">
                        <label class="form-check-label">
                            <input name="action"
                                   class="action form-check-input"
                                   type="checkbox"
                                   value="{{ value.id }}">
                            <i class="input-helper"></i>
                        </label>
                    </div>
                </td>
                <td class="py-1">
                    <img src="{{ value.avatar }}" alt="image"/>
                </td>
                <td>{{ value.title }}</td>
                <td>{{ value.sub_category_title }}</td>
                <td>{{ value.category_title }}</td>
                <td>
                    {% if value.status == 1 %}
                        <label class="active">Active</label>
                    {% else %}
                        <label class="inactive">Inactive</label>
                    {% endif %}
                </td>
                <td>
                    <a href="#">
                        <label class="edit">Edit</label>
                    </a>
                </td>
            </tr>
        {% endfor %}
    </tbody>
</table>

0 Comments

Leave a Reply

You must be logged in to post a comment.