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

hob*_*es3 1 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 %}
Run Code Online (Sandbox Code Playgroud)

user.profile只是从Django User到我的UserProfile.

但这似乎有点冗长和笨重.有更简单的方法吗?也许我应该编写自己的自定义上下文处理器并传递一个类似的变量is_admin,但我从来没有写过自定义上下文处理器...

San*_*4ez 6

您可以is_adminUserProfile模型添加方法,将业务逻辑移动到模型.

注意施工就好

{% if user.profile.user_types.all %}
    {% for user_type in user.profile.user_types.all %}
    ...
    {% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

点击2 sql查询到您的数据库.但with模板标签将它们减少到1次.

{% with types=user.profile.user_types.all %}
{% if types %}
    {% for user_type in types %}
    ...
    {% endfor %}
{% endif %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)

实际上最好的地方是模特.但是你应该了解django为你的目的提供什么(contrib.auth,权限,用户组).也许你重新发明轮子.

然后条件{% if user_type.name == "ad" %}不应该在你的python代码中硬编码(特别是在模板中).