在每个页面(base.html
)中,我想检查request.user
是否具有我的班级UserTypes
中的管理员角色并显示管理员链接。目前我这样做:
{% if user.profile.user_types.all %}
{% for user_type in user.profile.user_types.all %}
{% if user_type.name == "ad" %}
<li>
<a href="{% url admin:index %}" class="round button dark ic-settings image-left">Admin</a>
</li>
{% endif %}
{% endfor %}
{% endif %}
user.profile
只是从Django的User
转到我的UserProfile
。
但这似乎有点冗长和笨重。有更简单的方法吗?也许我应该编写自己的自定义上下文处理器并传递像is_admin
之类的变量,但我之前从未编写过自定义上下文处理器...
答案 0 :(得分:5)
您可以将方法is_admin
添加到UserProfile
模型中,将业务逻辑移动到模型中。
注意构造如
{% if user.profile.user_types.all %}
{% for user_type in user.profile.user_types.all %}
...
{% endfor %}
{% endif %}
向您的数据库发送2个sql查询。但with
模板标记会将其缩小为1次。
{% with types=user.profile.user_types.all %}
{% if types %}
{% for user_type in types %}
...
{% endfor %}
{% endif %}
{% endwith %}
实际上最好的地方是模特。但是你应该了解django为你的目的提供什么(contrib.auth,权限,用户组)。可能你重新发明轮子。
然后条件{% if user_type.name == "ad" %}
不应该在你的python代码中进行硬编码(特别是在模板中)。