带有ajax分页的Django Rest框架,如何在模板中切换数据?

时间:2018-08-20 11:29:25

标签: ajax django-rest-framework

使用ajax分页切换到下一页时,如何填写表格数据。

views.py

class PositionPageNumberPagination(PageNumberPagination): page_size = 1 max_page_size = 5

def get_paginated_response(self, data):
    context = {
        'next': self.get_next_link(),
        'previous': self.get_previous_link(),
        'count': self.page.paginator.count,
        'results': data,
    }
    return Response(context)

class PositionListAPIView(ListAPIView): queryset = Position.objects.all().order_by('name') serializer_class = PositionSerializer pagination_class = PositionPageNumberPagination

def list(self, request, *args, **kwargs):
    page = self.paginate_queryset(self.queryset)
    if page is not None:
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)

    serializer = self.get_serializer(self.queryset, many=True)
    return Response({'data': serializer.data})

position_list.html

{% extends 'index.html' %} {% load static %} {% block title %}The list of positions{% endblock %} {% block content %}     `     

<div class="pagination">
    <span>
        <a id="previous">previous</a>
        <a id="next">next</a>
    </span>

    <span id="count"></span>
</div>

<div>
    <button id="add_position">Add</button>
    <button id="edit_position">Edit</button>
    <button id="delete_position">Delete</button>
</div>

{% endblock %}

{% block addscript %}     <script src="{% static 'js/positions.js' %}"></script> {% endblock %}

urls.py

path('positions/', TemplateView.as_view(template_name='positions/position_list.html')),

position.js

当我单击“下一个元素”时,数据没有更改,但是API已启动(api / positions /?page = 2)

$.ajax({ url : "/api/positions/", dataType: "json", success : function (data) { let results = data.results; let positions = $('.positions');

    for (let i in results){
        positions.append(`<tr id=${results[i].id}><td>${results[i].name}</td></tr>`)
    }

    $('#count').html(data.count);
    $('#previous').attr('href', data.previous);
    $('#next').attr('href', data.next);
    }

});

0 个答案:

没有答案