【问题标题】:How do I use AJAX for pagination in Django-Tables2?如何在 Django-Tables2 中使用 AJAX 进行分页?
【发布时间】:2018-04-06 02:32:19
【问题描述】:

我正在使用 django-tables2,我试图在不加载另一页的情况下显示下一页的数据。我认为可以使用 AJAX。

从我的发现看来,这可能是不可能的。 已经有人讨论过这个Support AJAX sorting/pagination

有什么我应该看的吗?

【问题讨论】:

  • 绝对可以。创建一个生成表格的视图,并让 JavaScript 处理对该表格上链接的点击;然后,获取表的刷新视图并替换它(如果需要,再次添加处理程序)。
  • 从您发布的链接来看,他们似乎没有添加任何 ajax 支持(哇,这个问题已经超过 7 年了)。我知道这不是您要寻找的答案,但为什么不使用 Bootstrap 表呢?这样您就可以更好地控制布局。之后,您可以使用标准的 Django 分页并更轻松地使用 ajax 请求。它也会看起来更漂亮。
  • 如果您对此感兴趣,也可以看看datatables.net

标签: django django-tables2


【解决方案1】:

这是可能的,但它并不那么容易,因为 django-tables2(和一般的 django)更适合服务器端渲染的世界。我将在这里草拟一个解决方案,并为我的博客 (https://spapas.github.io) 考虑这个有趣的主题:

  • 您需要覆盖将要使用的 django-tables2 模板。您不能使用默认的,因为它的分页是由普通链接完成的。您应该覆盖它以使用 Ajax 调用 - 更多信息请查看此问题Is it possible to custom django-tables2 template for a specific page in this case?。您要做的是禁用页面链接的默认链接功能,并通过 ajax 调用它们。根据您的操作方式,这可以通过视图模板中的script 来完成,而根本不需要覆盖表格模板。

  • 您需要修改视图以检测它是否被 ajax 调用(即通过您在上面定义的这些分页按钮)并每次返回不同的模板。如果它被正常调用,那么您只需渲染您的经典模板。如果它是通过 ajax 调用的,那么它将只返回仅包含表的 html 部分。

  • 现在在您的普通模板中,您将把表格放在名为(f.e)#the_tablediv 中 - 当用户单击分页链接时,您将执行 ajax 调用,响应将包含表格 - 然后您将用您刚刚收到的内容替换 #the_table div 的内容。

因此,您的视图应该有两个模板,您的 view.html 类似于:

{% extends base.html %}
{% block content %}
blah blah

<div id='the_table'>
    {% include 'partial_table.html' %}
</div>
{% endblock %}

{% block extra_script %}
    <script>
    // You can do something like (NOT TESTED):
    // I don't remember if the pagination links belong to a class 
    // if not you may want to add that class yourself
    $('pagination-link').click(function(e) {
        // Don't follow the link
        e.preventDefault();
        // Do the ajax request
        $.get($(this).attr("href"), function(data) {
            // Replace the table with what you received
            $('#the_table').html(data)
        });

    });
    </script>
{% endblock %}

还有你的partial_table.html

{% load django_tables2 %}
{% render_table table %}

现在在您看来,如果您正在使用 CBV,那么您将必须使用上面定义的 template_name = view.html 并像这样覆盖 get_template_names

def get_template_names(self):
    # Sometimes the is_ajax() is not working properly so if it doesn't 
    # just pass the ajax_partial query parameter to your ajax request
    if self.request.is_ajax() or self.request.GET.get('ajax_partial'):
        return 'partial_table.html'
    return super().get_template_names()

更多信息可以在我的 Django CBV 指南的这个食谱中找到:https://spapas.github.io/2018/03/19/comprehensive-django-cbv-guide/#implement-a-partial-ajax-view

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-09-29
  • 2012-12-26
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多