javascript - 将 django 模板变量传递给 js 数据表

标签 javascript django python-3.x datatables django-templates

您好,我想使用 JS 数据表库创建表。

将模板中的值传递给 js 脚本时遇到问题。 我从我想要显示的表中创建了 JSON 对象。 它已正确传递到模板,当我显示它时一切都很好,但是当尝试将它传递到脚本时没有发生任何事情并且我得到了空表。

我就是这样做的:

class VotesList(generic.ListView):
    model = Vote
    template_name = 'votes-list.html'
    def get_context_data(self, **kwargs):
        votes = Vote.objects.all().values('user', 'group', 'council')
        votes_json = json.dumps(list(votes))
        context = super(VotesList, self).get_context_data(**kwargs)
        context['orderby'] = self.request.GET.get('orderby', 'created_date')
        context['json_data'] = votes_json

    return context

模板:

{% block javascript %}
{% load static %}

<script type="text/javascript">
$(document).ready(function() {

    var json=JSON.parse('{{ json_data | safe }}');
    $('#votes_list').DataTable({
       data: json,
        columns:[
        { title: "user" },
        { title: "group" },
        { title: "council" }]
    } );
};

</script>

{% endblock %}

{% block content %}

    <p>{{ json_data | safe }}</p> <<< here data is printed fine
    {% if vote_list %}

        <table id="votes_list" class="display", style="width:100%">
            <thead>
                <tr>
                    <th>Właściciel</th> 
                    <th>Grupa</th> 
                    <th>Rada</th> 
                </tr>
            </thead>

        </table>

    {% else %}
        <p>Brak głosowań!</p>
    {% endif %}

{% endblock %}

输出数据如下所示:

[{"user": 2, "group": 1, "council": 1}, {"user": 2, "group": 2, "council": 1}, {"user": 3, "group": 1, "council": 1}, {"user": 2, "group": 1, "council": 1}, {"user": 2, "group": 2, "council": 2}, {"user": 1, "group": 1, "council": 2}, {"user": 3, "group": 1, "council": 1}, {"user": 2, "group": 1, "council": 1}, {"user": 1, "group": 1, "council": 2}, {"user": 1, "group": 2, "council": 1}, {"user": 1, "group": 1, "council": 1}, {"user": 1, "group": 1, "council": 1}]

我的第二个问题是关于其他事情: 我存储了大量信息作为选择:

STATUS_INACTIVE = 0
STATUS_ACTIVE = 1
STATUS_FINISHED = 2
STATUS_CHOICES = (
    (STATUS_INACTIVE, 'Inactive'),
    (STATUS_ACTIVE, 'Active'),
    (STATUS_FINISHED, 'Finished'),
)

如何将人类可读的值(“非事件”)传递给上面的 JSON,而不是数字?

最佳答案

对于第一个问题,尝试添加 <tbody></tbody>之后</thead>标签。重新运行代码。

For DataTables to be able to enhance an HTML table, the table must be valid, well formatted HTML, with a header (thead) and a single body (tbody).

还有另一种更简单的方式来呈现数据表。

View .py-

context['json_data'] = votes # no need to use json.dumps


在 html 中-

   <table id="votes_list" class="display", style="width:100%">
        <thead>
            <tr>
                <th>Właściciel</th> 
                <th>Grupa</th> 
                <th>Rada</th> 
            </tr>
        </thead>
        <tbody>
            {% for data in json_data %}
                <tr>{{ data.user }}</tr>
                <tr>{{ data.group }} </tr>
                <tr>{{ data.council }} </tr>
            {% endfor %}
        </tbody>
   </table>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#votes_list').DataTable();
        }
    </script>

对于第二个问题 -

{% if data.user == 1 %}
   Active
{% elif data.user == 2%}
   Inactive
{% else %}
   Finished
{% endif %}
OR 
{% if data.group == 1 %}
   {{ status_dict.0 }}
{% elif data.group == 2%}
   {{ status_dict.1 }}
{% else %}
   {{ status_dict.2 }}
{% endif %}

>>>status_dict = dict(STATUS_CHOICES)
{0: 'Inactive', 1: 'Active', 2: 'Finished'}

在数据表中 - 您可以应用相同的逻辑。例如-

  "columns": [
    { "data": "engine" },
    { "data": "browser" },
    {
      "data": "platform",
      "render": function(data, type, row, meta) { 
                      if(true)
                          return “display this” 
                      };
                      return “false"
    }
  ]

关于javascript - 将 django 模板变量传递给 js 数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51408948/

相关文章:

javascript - 如何减少文本行之间的空间量

javascript - 推送路线时将对象作为 Prop 传递

javascript - 2D 数组到 3D 数组 Javascript(Google 脚本)

python - Django 分页中的 EmptyPage 错误

python - 正确理解 pexpect 的异步

python - 如何搜索单词而不是整个组合

python-3.x - 在 Pandas DataFrame 的每一行中添加具有最受欢迎字符串值的新列

javascript - 获取“未捕获的类型错误 : Cannot read property 'value' of null"on Google Places API

django - 如何从django下拉框中获取值?

python - 如何以编程方式创建 django `models.Textchoices`?