javascript - 替换 HTML 表格中的值?

标签 javascript jquery html django django-simple-history

我正在制作一个 HTML 表格来显示已添加、删除和更改的盒子(在库房中)。标题表示盒子的所有者、发生的更改类型以及盒子的新内容。

我使用 Django 作为我的后端。

我可以将“Type of Change”中的值翻译成英文单词而不是符号(~、- 和 +)吗?我正在使用 Django simple-history 来记录对模型的更改,并返回这些符号。我希望我的表格显示为“已更改”、“已删除”和“已添加”,而不是“~”、“-”和“+”。

My table

这是 View .py:

def dashboard(request):
    box_content_history = Box.history.all().order_by('-history_date')
    return render(request, 'main_app/dashboard.html', {""box_content_history":box_content_history})

HTML:

<table id="asset_changes_datatable">
    <thead>
        <tr>
            <th>Owner</th>
            <th>Type of Change</th>
            <th>Box Contents</th>
        </tr>
   </thead>
   <tbody>
   {% for item in box_content_history %}
        <tr>
            <td>{{ item.project_assigned_to }}</td>
            <td>{{ item.history_type }}</td>
            <td>{{ item.box_contents }}</td>
        </tr>
   {% endfor %}
   </tbody>
</table>

最佳答案

正如评论中已经提到的,只需在模板中将 {{ item.history_type }} 更改为 {{ item.get_history_type_display }} 即可。

这个魔法是什么?它从何而来?

这实际上是普通的 django 功能,并在 Model instance reference 中进行了解释。 。

For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.

为什么它适用于 django-simple-history 的 history_type 字段?

非常简单:history_type 字段具有前面提到的choices 设置。我通过查看 their source 进行了检查。代码在github上。

"history_type": models.CharField(
    max_length=1,
    choices=(("+", _("Created")), ("~", _("Changed")), ("-", _("Deleted"))),
),

关于javascript - 替换 HTML 表格中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54206703/

相关文章:

jquery - 如何获取(打印)元素相对于其父元素的索引

javascript - settimeout 和cleartimeout 单击即可开始计时

html - 始终在我最后一个列表项 "See more links"下方留出 10px 的底部边距

javascript - 使用哈希打开 shadowbox.js 弹出窗口

javascript - JQuery 内联调用多个函数

javascript - 要求另一家商店中的商店不起作用

javascript - 如何使 html 输入字段的占位符文本可编辑?

javascript - 获取不带 "id"属性的 td 的内容

javascript - 使用其他网站元素的 id javascript

javascript - 刷新后 React-Redux 状态丢失