2012-05-07 41 views
0

在每个页面(base.html)中,我想检查request.user是否具有来自我的类​​UserTypes的管理员角色并显示管理员链接。目前,我做这样的事情:有没有更简单的方法来检查Django模板中的M2M值?

{% 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

也许一个愚蠢的问题,但为什么不只是依靠'User.is_superuser'?或者,如果“管理员”是指任何有权访问Django管理员User.is_staff的用户。看起来你只是增加了额外的复杂性,没有很好的理由。 –

回答

5

您可以添加方法is_adminUserProfile模式转向业务逻辑模型。

注意,像建设

{% 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代码(特别是在模板中)硬编码。

相关问题