有关Django模板无法使用perms变量问题的解决方法

正常情况下,已登录用户权限保存在模板{{perms}}变量中,是权限模板代理的django.contrib.auth.context_processors.PermWrapper的一个实例,具体可以查看django/contrib/auth/context_processors.py源码。

举例:
{% if perms %}
Welcome
{% else %}
You do not have permission to do anything here!
{% endif %}
发现{{perms}}变量压根就不存在。

经测试发现,使用 return render(request, 'fms/fms_add.html', locals()) 可以获得权限信息

return render_to_response( 'fms/fms.html', locals()) 则不能获得权限信息。

render VS render_to_response

render是比render_to_response更便捷渲染模板的方法,会自动使用RequestContext, 而后者需要手动添加,才能获取权限信息。
即 return render_to_response( 'fms/fms.html', locals(), context_instance=RequestContext(request))

其中 RequestContext是django.template.Context的子类,接受 request 和 context_response, 从而将上下文填充渲染到模板问题已经很明确,由于使用了render_to_response方法。没有手动添加context_instance=RequestContext(request) 导致模板不能使用{{perms}}变量。

综上所述:获取perms变量的两种方法

1:return render(request, 'fms/fms_add.html', locals())
2:return render_to_response( 'fms/fms.html', locals(), context_instance=RequestContext(request))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容