gpt4 book ai didi

python - 如何在 Django 中进行 ajax 分页?

转载 作者:行者123 更新时间:2023-12-02 19:26:52 24 4
gpt4 key购买 nike

!!我有一个名为blog !!

的模型
class blog(models.Model):
image = models.ImageField(upload_to='Media/awards')
title = models.CharField(max_length=255,blank=True)
content = models.TextField(blank=True)

在前端我有

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

<!-- pagination design start -->
<div class="blog_bottom_pagination">
<div class="counter">/</div>
<button class="paginate left"><i class="fas fa-angle-left"></i></button>
<button class="paginate right">
<i class="fas fa-angle-right"></i>
</button>
</div>
<!-- pagination design end -->

我没有找到任何引用如何在不刷新页面的情况下实现分页并在该 div 部分中一次呈现两个数据。并通过按钮向右和向左分页以获取下两个数据,并将替换该 div 中的那些先前数据....提前感谢您

最佳答案

所以 View 端应该是这样的:

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

blog_objects= Blog.objects.filter()

paginator = Paginator(blog_objects, 10)
page = request.GET.get('page', 1)

try:
blogs = paginator.page(page)
except PageNotAnInteger:
blogs = paginator.page(1)
except EmptyPage:
blogs = paginator.page(paginator.num_pages)

page_list = blogs.paginator.page_range

在模板上触发 ajax 函数的按钮:

{% for i in page_list %}
<button onclick="ajax_function('{{i}}','{{title}}')">{{i}}</button>

注意“i”是 ajax 函数的页码,“title”是查询的参数。

来自模板的 Ajax 函数在最后......

Ajax View :

def paginate(request):
page= request.GET.get('page', None)
title= request.GET.get('title', None)

starting_number= (page-1)*10
ending_number= page*10

"here you should multiply the 'page' by the number of results you want per page, in my example it's 10"



result= Blog.objects.filter(title= title)[starting_number:ending_number]

"By [starting_number:ending_number] we specify the interval of results. Order them by date or whatever you want"
data={result}

return JsonResponse(data)

结果对象现在被发送到 html 端,现在是 ajax 函数的时间了:

function ajax_function(page,title) {
$.ajax({
url: '/ajax/paginate/',
type: "get",
data: {
'page': page,
'title': title,

},
dataType: 'json',
success: function (data) {
$('#id-of-your-choice').empty();
for (i = 0; i < data.result.length; i++) {
$('#id-of-your-choice').append(i)
}
"at first the function cleans the old childs of the element on which you display your results then it appends the new page's content by iterating over 'results'"

希望这就是您要找的,玩得开心!

关于python - 如何在 Django 中进行 ajax 分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62305524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com