模板中的Django条件详细信息

时间:2020-08-14 09:12:45

标签: django django-models django-forms django-views django-templates

在我的Django应用程序中,有些用户使用department codes,我想向这些用户显示有关模板的不同详细信息,但是超级用户应该可以看到所有内容。这是我的代码:

template.html

{% if user.is_superuser or user.department_code=1%}
<p>Your department code is 1 or you are a superuser</p>
{% elif user.is_superuser or user.department_code=2%}
<p>Your department code is 2 or you are a superuser</p>
{% else %}
<p> You are a superuser</p>
{% endif %}

在这种情况下,我作为超级用户只能看到第一段。我该怎么做呢?

1 个答案:

答案 0 :(得分:2)

您的问题是由您使用{% elif %}引起的。

如果您是超级用户,则将检查第一个条件,该条件的结果为True,然后不再检查您随后的{% elif %}{% else %}。仅当第一个条件为{% elif %}时,才考虑第二个False,这就是为什么如果您不是超级用户,它会起作用的原因。为了使{% else %}触发,前两个条件必须均为False。例如,如果您以非超级用户身份登录并且部门代码为3,则可能会发生这种情况。

只需将您的{% elif %}替换为{% if %},它就会起作用。

{% if user.is_superuser or user.department_code == 1 %}
    <p>Your department code is 1 or you are a superuser</p>
{% endif %}
{% if user.is_superuser or user.department_code == 2 %}
    <p>Your department code is 2 or you are a superuser</p>
{% endif %}
{% if user.is_superuser %}
    <p> You are a superuser</p>
{% endif %}

在相等性检查中您还缺少了“ =”,请注意我在每种情况下如何使用两个而不是一个。

相关问题