【问题标题】:set attribute of a row in django-tables2 to record.id将 django-tables2 中一行的属性设置为 record.id
【发布时间】:2016-04-08 05:51:53
【问题描述】:

我正在尝试将 django-tables2 中一行的属性设置为当前记录的 id。

为此,我修改了 table.html 模板中的一行:

<tr row_id="{{ record.id }}" class="{{ forloop.counter|divisibleby:2|yesno:"even,odd" }}">

但这在 html 结果中给了我空的 row_id="" 。怎么了?

【问题讨论】:

  • 您能否评论以下建议是否对您有用,或者您是否找到了不同的方法?
  • 嗨!我没有测试过这个建议。我为我的任务使用了单元格的属性。

标签: django-tables2


【解决方案1】:

tables2 row 对象不是记录。但记录在其中。所以你可以这样做:

<tr id="row_{{ row.record.id }}" class="{{ forloop.counter|divisibleby:2|yesno:"even,odd" }}">

或者使用数据属性

<tr data-record-id="row_{{ row.record.id }}" class="{{ forloop.counter|divisibleby:2|yesno:"even,odd" }}">

这绝对有效..我正在使用它。

还可以在这里查看(最后一个)答案:django-tables2 specify different properties for different rows,它建议使用自定义渲染方法将一些 html 添加到每行中的单元格。这样您就不必维护自定义的 tables2 模板。然后在 jquery 的帮助下,很容易找到包含 id 的元素。如果用户单击该行,或者您想做的任何事情...

【讨论】:

    【解决方案2】:

    django-tables2 table.html 的 for 变量的默认名称(正如我们在 https://github.com/bradleyayers/django-tables2/blob/master/django_tables2/templates/django_tables2/table.html#L25 看到的那样)是 row(而不是用于 TemplateColumnrecord)。

    您尚未共享您的table.html 模板,但我认为这可能是您看到一个空的row_id 的原因。那么你可以尝试将row_id="{{ record.id }}" 更改为row_id="{{ row.id }}" 吗?

    【讨论】:

    • 我刚刚尝试过,但没有成功(返回 row_id="-")。
    • 您的数据是否真的有一个名为“id”的字段?
    • 是的,确实如此。 (请注意,SO 不会让我只发布“是”,因为它没有足够的字符)
    • 它也不适用于另一个主键设置为字符串的模型。在那种情况下,我只会得到row_id,什么都没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多