如何使Django规则在模板中工作?

时间:2019-03-20 17:22:16

标签: django permissions django-rules

使用Django-Rules时,您可以检查视图中的权限。但是我的总是返回假。以下示例中的代码始终显示“ bar”,但必须显示“ foo”:

  {% extends 'home/base.html' %}
  {% load rules %}
  {% has_perm 'anApp.can_access_something' user as can_access_something %}

  {% block content %}
      {% if can_access_something %}
          <p>foo</p>
      {% else %}
          <p>bar</p>
      {% endif %}
      ...
  {% endblock %}

我的rules.py看起来像这样:

@rules.predicate
def testrule(user):
    return True

rules.add_perm('anApp.can_access_something', testrule)

所以总是会返回true。

1 个答案:

答案 0 :(得分:2)

以下行必须在一个块中:

{% has_perm 'anApp.can_access_something' user as can_access_something %}

这将正确显示'foo':

{% extends 'home/base.html' %}
{% load rules %}

{% block content %}
    {% has_perm 'anApp.can_access_something' user as can_access_something %}
    {% if can_access_something %}
        <p>something</p>
    {% else %}
        <p>something else</p>
    {% endif %}
    ...
{% endblock %}