Django管理员,如何在django模板中正确检查用户的权限?

Cha*_*iam 3 permissions django-templates django-admin

新手在这里.我的申请名称是ccad.型号名称为logbook.用户A无权从可用的用户权限编辑,添加或删除日志模型.

所以我尝试隐藏保存,保存并继续编辑,保存并添加来自用户A的其他按钮.

我跟着我在SO发现的建议. 这是来自Sid回答的picomon调查.和丹尼尔一样的询问.

我最终将下面的代码写入我的模板.

change_form.html位于{{template folder}}/admin/app_name/model_name /

 {% if perms.ccad.add_logbook %}
    <li><input type="submit" value="{% trans 'Save ' %}" class="grp-button grp-default" name="_save" {{ onclick_attrib }}/></li>     
    <li><input type="submit" value="{% trans 'Save and add another' %}" class="grp-button" name="_addanother" {{ onclick_attrib }} /></li>
    <li><input type="submit" value="{% trans 'Save and continue editing' %}" class="grp-button" name="_continue" {{ onclick_attrib }}/></li>        
 {% endif %}
Run Code Online (Sandbox Code Playgroud)

但是没有权限的用户仍然可以看到我提到的按钮.

我也尝试改变{% if perms.ccad.add_logbook %},以{% if perms.ccad.can_add_logbook %}与无济于事.

什么是最好的方法呢?

小智 5

首先检查模板上下文中的perms变量.添加...{{ perms }}...模板可见的位置.它应该像这样渲染...<django.contrib.auth.context_processors.PermWrapper object at X>....

如果不是这种情况,则表示您缺少模板中的权限.

验证您的设置TEMPLATE_CONTEXT_PROCESSORS元组是否包含django.contrib.auth.context_processors.auth.

还要确保在渲染模板时使用a RequestContext而不是a Context.

如果你最终看到一个PermWrapper但你的权限检查仍然无效,请将之前的调试更改为...{{ perms.ccad }}....这应输出类似于"set([u'ccad.add _...',...])的内容.

如果没有,则可能不会调用您的应用ccad.

最后在创建if条件之前,请确保权限返回"... {{perms.ccad.add_logbook}}} ...".这应该返回True或False.

现在我到最后我注意到你的问题是另一种方式,到目前为止我写的所有内容都没用.:)

添加{{ user.is_superuser }}到您的模板.如果为True,则当前用户具有超级用户权限,即使对于,也始终返回True{{ perms.omg.can_facepalm }}