【问题标题】:Dynamic tables with Django tables2带有 Django 表的动态表2
【发布时间】:2017-10-17 01:48:18
【问题描述】:

我正在使用 django_tables2 包在我的页面上显示表格。我有两组要动态显示的数据。

<Table_1_A>
<Table_1_B>

<Table_2_A>
<Table_2_B>

<Table_n_A>
<Table_n_B>

在我的views.py中我有:

primary_keys = {1, 2, ... n} # these are not simple or ordered integers
tables_A = {}
tables_B = {}

for primary_key in primary_keys:
    tables_A['primary_key'] = TableA(table_A_queryset.filter(pk=primary_key))
    RequestConfig(request).configure(tables_A[primary_key])

    tables_B['primary_key'] = TableB(table_B_queryset.filter(pk=primary_key))
    RequestConfig(request).configure(tables_B[primary_key])

return render(request, 'index.html', {'primary_keys': primary_keys, 'tables_A ': tables_A , 'tables_B ': tables_B })

TableA 和 TableB 在我的 tables.py 中定义

在我的 templatetabs 文件夹中,我有 tags.py:

@register.assignment_tag
    def get_table(table, primary_key):
return table.get(primary_key)

终于在我的 index.html 中:

{% load render_table from django_tables2 %}
{% load tags %}

{% block content %}

    {% for primary_key in primary_keys %}
         <div class="data_tables">
            {% get_table tables_A primary_key as table_A %}
            {% render_table table_A %}
            <br>
            <br>

            {% get_table tables_B primary_key as table_B%}
            {% render_table table_B%}
        </div>
    {% endfor %}

{% endblock content %}

我在 pycharm 中运行 django 1.11,当我在 pycharm 中运行时,它工作得很好。当我在 debian 服务器上运行它时,我得到了错误。如果有任何内容传递到 primary_key、tables_A 和 tables_B,我会收到 500 内部服务器错误。如果这些字典是空的,我会得到:'第 19 行的无效块标记:'get_table',预期为'empty'或'endfor'。您是否忘记注册或加载此标签?'

这在服务器上不起作用但在本地起作用的任何原因?或者有更好的方法吗?

【问题讨论】:

    标签: python django django-templates django-views django-tables2


    【解决方案1】:

    我能够使用列表而不是字典来解决这个问题。

    primary_keys = [1, 2, ... n] # these are not simple or ordered integers
    tables_A = []
    tables_B = []
    
    for idx, primary_key in enumerate(primary_keys):
        tables_A.append(TableA(table_A_queryset.filter(pk=primary_key)))
        RequestConfig(request).configure(tables_A[idx])
    
        tables_B.append(TableB(table_B_queryset.filter(pk=primary_key)))
        RequestConfig(request).configure(tables_B[idx])
    
    return render(request, 'index.html', {'tables_A ': tables_A , 'tables_B ': tables_B })
    

    我根本不需要使用模板标签

    {% load render_table from django_tables2 %}
    
    {% block content %}
    
        {% for val in table_A %}
             <div class="data_tables">
                {% render_table table_A.pop %}
                <br>
                <br>
                {% render_table table_B.pop %}
            </div>
        {% endfor %}
    
    {% endblock content %}
    

    【讨论】:

      猜你喜欢
      • 2010-09-26
      • 2019-09-21
      • 1970-01-01
      • 2015-11-08
      • 2017-03-18
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 2020-11-16
      相关资源
      最近更新 更多