是否有更短的方法来检查Django模板中的M2M值?

时间:2012-05-07 19:01:41

标签: django django-templates django-context

在每个页面(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之类的变量,但我之前从未编写过自定义上下文处理器...

1 个答案:

答案 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代码中进行硬编码(特别是在模板中)。