Django+Paginator+ajax dynamic load paging

Keywords: Programming Django JQuery

How to switch pages without refreshing the whole page?

In fact, the implementation is very simple. The idea is: how many pages are the Paginator backend split (for example: how many pages in total; how many pages are the current page; what is the content of this page?) , through Ajax interactive data display.

Two core objects of Paginator (Paginator, page)

Paginator

  • Per page: display the number of records per page
  • count: total number of data
  • Num pages: total pages
  • page_range: index range of total pages, such as: (1,10), (1200)
  • Page: page objectpage (2) represents the object of the second page of data

Page

  • Has "next: is there a next page
  • Has previous: whether there is a previous page
  • Next page number: next page number
  • Previous page number
  • Object list: current page data list after paging
  • number: current page
  • paginator: paginator object, parent object

Paste code, hope to learn and communicate with you.

urls.py

from app import views

urlpatterns = [
    path('console/', views.console, name='console'),
]

views.py

from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, InvalidPage
from 
# The 'user' here is the data displayed for calling models

def console(request):
	# All data
    user_list = User.objects.all()
    # Paging function, 7 pieces of data per page
    paginator = Paginator(user_list, 7)
    if request.method == 'GET':
    	# Data on the first page is displayed by default
    	users = paginator.page(1)
    	return render(request, 'system/console.html', {'users': users})
   	# Ajax data interaction
    if request.is_ajax():
        page = request.GET.get('page')
        try:
            users = paginator.page(page)
        # If the number of pages is not an integer, return to the first page
        except PageNotAnInteger:
            users = paginator.page(1)
        # If the number of pages does not exist / is illegal, return to the last page
        except InvalidPage:
            users = paginator.page(paginator.num_pages)
        user_li = list(users.object_list.values())
        # They are whether there is false/true on the previous page, whether there is false/true on the next page, the total number of pages, and the data of the current page
        result = {'has_previous': users.has_previous(),
                  'has_next': users.has_next(),
                  'num_pages': users.paginator.num_pages,
                  'user_li': user_li}
        return JsonResponse(result)

console.html

The style uses the home-made framework UI (layui), including static table and button style layui portal

<link rel="stylesheet" href={% static 'layui/css/layui.css' %}>
<table class="layui-table">
    <thead>
    <tr>
        <th>user</th>
        <th>identity</th>
        <th>Gender</th>
        <th>Telephone</th>
        <th>mailbox</th>
        <th>Recent login</th>
        <th>Adding time</th>
        <th>Update time</th>
    </tr>
    </thead>
    <tbody id="tbody">
    //Default first page content
    {% for u in users %}
        <tr>
            <td>{{ u.username }}</td>
            <td>{{ u.is_rank }}</td>
            <td>{{ u.sex }}</td>
            <td>{{ u.phone }}</td>
            <td>{{ u.email }}</td>
            <td>{{ u.last_login }}</td>
            <td>{{ u.date_joined }}</td>
            <td>{{ u.update_time }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>
<div style="text-align: center;margin: 5% 0;">
    <form id="page" action={% url 'console' %}>
        <a class="first_page">
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">Previous page</button>
        </a>
		
		// Convenient pages
        {% for num in users.paginator.page_range %}
            <a class="now_page">
                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">{{ num }}</button>
            </a>
        {% endfor %}

        <button id="num_pages" type="button" class="layui-btn layui-btn-primary layui-btn-sm">
            common{{ users.paginator.num_pages }}page
        </button>

        <a class="last_page">
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">next page</button>
        </a>
    </form>
</div>

Part ajax

Tool jQuery 3.4.1 jQuery portal

<script>
    $(function () {
        // ajax paging
        let now_page = 1;
        $('.first_page button').removeClass('layui-btn-primary').addClass('layui-btn-disabled');
        $('.now_page button').first().removeClass('layui-btn-primary').addClass('page_this');
        //Previous page
        $('.first_page').click(function () {
            now_page -= 1;
            if (now_page < 1) {
                now_page = 1;
                return false
            } else {
                $('.page_this').parent().prev().click();
            }
        });
        //next page
        $('.last_page').click(function () {
            let num_pages = $('.now_page button').last().text();
            now_page += 1;
            if (now_page > parseInt(num_pages)) {
                now_page -= 1;
                return false
            } else {
                $('.page_this').parent().next().click();
            }
        });
        //Switch page
        $('.now_page').click(function () {
            now_page = parseInt($(this).children('button').text());
            $('.now_page button').removeClass('page_this').addClass('layui-btn-primary');
            $(this).addClass('page_this');
            $(this).children('button').removeClass('layui-btn-primary').addClass('page_this');
            page_click()
        });

        function page_click() {
            let page_form = $('#page');
            $.ajax({
                type: 'get',
                url: page_form.attr('action'),
                data: {page: now_page},
                success: function (data) {
                    $('#tbody tr').remove();
                    $('#Num [pages'). HTML ('total '+ data. Num [pages +' pages');
                    if (data.has_previous === true) {
                        $('.first_page button').removeClass('layui-btn-disabled').addClass('layui-btn-primary');
                    } else {
                        $('.first_page button').removeClass('layui-btn-primary').addClass('layui-btn-disabled')
                    }
                    if (data.has_next === true) {
                        $('.last_page button').removeClass('layui-btn-disabled').addClass('layui-btn-primary');
                    } else {
                        $('.last_page button').removeClass('layui-btn-primary').addClass('layui-btn-disabled');
                    }
                    $.each(data.user_li, function (index, user) {
                        let a = '<td>';
                        let b = '</td>';
                        let body = a + user.username + b + a + user.is_rank + b + a + user.sex + b + a + user.phone + b + a + user.email + b + a + user.last_login + b + a + user.date_joined + b + a + user.update_time + b;
                        $('#tbody').append('<tr>' + body + '</tr>');
                    });
                }
            })
        }
    })
</script>

Design sketch

Maybe there are more advanced methods. This is just one of them. I hope to share and learn with you.

Posted by retoto on Mon, 10 Feb 2020 06:56:11 -0800