【问题标题】:django-tables2 permissions in TemplateColumnTemplateColumn 中的 django-tables2 权限
【发布时间】:2019-01-12 12:09:31
【问题描述】:

我觉得我已经阅读了一百遍,但我仍然无法弄清楚如何在 django-tables2 TemplateColumn 中使用权限。

我的目标是能够根据用户在给定模型上可能拥有或不拥有的权限来呈现列中的按钮。这对我来说听起来并不复杂,从我读过的内容来看,我应该能够使用{% if perms.myapp.delete_mymodel %} 之类的东西来实现我想做的事情。

这是我试图按预期工作的代码:

import django_tables2 as tables


MY_MODEL_ACTIONS = """
{% if perms.myapp.change_mymodel %}
<a href="{% url 'myapp:my_model_edit' pk=record.pk %}" class="btn btn-sm btn-warning"><i class="fas fa-edit"></i></a>
{% endif %}
{% if perms.myapp.delete_mymodel %}
<a href="{% url 'myapp:my_model_delete' pk=record.pk %}" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></a>
{% endif %}
"""


class MyModelTable(tables.Table):
    # some columns
    actions = tables.TemplateColumn(
        verbose_name="",
        template_code=MY_MODEL_ACTIONS,
    )

    class Meta(BaseTable.Meta):
        model = MyModel
        fields = (
            # some columns
            "actions",
        )

在呈现表格时不会触发任何问题,但该列只是不显示任何按钮(是的,我确实有权显示它们)。删除{% if … %} 子句,从而删除权限检查,当然可以看到按钮。

【问题讨论】:

    标签: django python-3.x django-templates django-tables2


    【解决方案1】:

    这个问题有点棘手。我定义了自己的模板来呈现表格,并没有在其中使用 {% render_table table %} 标记。因此,无法从 TemplateColumn 代码访问上下文。

    为了解决这个问题,我稍微更改了我的模板并将我的表格渲染自定义代码移动到另一个模板文件。之后我使用了render_table 这样的标签{% render_table table 'includes/table.html' %}

    在此之后,我在上面的专栏中提到的代码工作正常,权限按预期兑现。

    【讨论】:

      【解决方案2】:

      是什么将perms 添加到您的上下文中?TemplateColumns 与调用模板{{ render_table table }} 的上下文不同,因此您必须更明确一点。

      The documentation for render_table mentions it will attach the context of the calling template to table.context,所以这应该可以解决您的问题:

      MY_MODEL_ACTIONS = """
      {% if table.context.perms.myapp.change_mymodel %}
          <a href="{% url 'myapp:my_model_edit' pk=record.pk %}" class="btn btn-sm btn-warning"><i class="fas fa-edit"></i></a>
      {% endif %}
      {% if table.context.perms.myapp.delete_mymodel %}
          <a href="{% url 'myapp:my_model_delete' pk=record.pk %}" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></a>
      {% endif %}
      """
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-03
        • 1970-01-01
        • 2021-03-26
        • 2016-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多