源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-04-12 15:30 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:解决Django模板无法使用perms变量问题的方法
[b]前言[/b] 本文主要给大家介绍了关于Django模板无法使用perms变量的解决方法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 [b]解决方法:[/b] 首先,在使用Django内置权限管理系统时,settings.py文件要添加
INSTALLED_APPS添加:
'django.contrib.auth',

 
MIDDLEWARE添加:
'django.contrib.auth.middleware.AuthenticationMiddleware',

'django.contrib.auth.context_processors.auth',
TEMPLATES = [
 {
  'BACKEND': 'django.template.backends.django.DjangoTemplates',
  'DIRS': [os.path.join(BASE_DIR, 'templates')],
  'APP_DIRS': True,
  'OPTIONS': {
   'context_processors': [
    'django.template.context_processors.debug',
    'django.template.context_processors.i18n',
    'django.template.context_processors.media',
    'django.template.context_processors.static',
    'django.template.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
    'django.template.context_processors.request',
    'django.contrib.auth.context_processors.auth',
   ],
  },
 },
]
[b]如何在模板进行权限检查呢?[/b] 根据官网说明 [url=https://docs.djangoproject.com/en/1.11/topics/auth/default/#permissions]https://docs.djangoproject.com/en/1.11/topics/auth/default/#permissions[/url] ,已登录用户权限保存在模板[code]{{ perms }}[/code]变量中,是权限模板代理[code]django.contrib.auth.context_processors.PermWrapper[/code]的一个实例,具体可以查看django/contrib/auth/context_processors.py源码 [b]测试用例:[/b] [img]http://img.1sucai.cn/uploads/article/2018010710/20180107100133_0_13024.jpg[/img]   测试过程中,发现[code]{{ perms }}[/code]变量压根不存在,没有任何输出;好吧,只能取Debug Django的源码了
def auth(request):
 """
 Returns context variables required by apps that use Django's authentication
 system.

 If there is no 'user' attribute in the request, uses AnonymousUser (from
 django.contrib.auth).
 """
 if hasattr(request, 'user'):
  user = request.user
 else:
  from django.contrib.auth.models import AnonymousUser
  user = AnonymousUser()
 print(user, PermWrapper(user), '-----------------------')
 return {
  'user': user,
  'perms': PermWrapper(user),
 }
测试访问接口,发现有的接口有打印权限信息,有的没有,似乎恍然醒悟 可以打印权限信息的接口返回:
 return render(request, 'fms/fms_add.html', {'request': request, 'form': form, 'error': error})
不能打印权限新的接口返回:
 return render_to_response( 'fms/fms.html', data)
[b]render和render_to_response区别[/b] render是比render_to_reponse更便捷渲染模板的方法,会自动使用RequestContext,而后者需要手动添加:
return render_to_response(request, 'fms/fms_add.html', {'request': request, 'form': form, 'error': error},context_instance=RequestContext(request))
其中RequestContext是[code]django.template.Context[/code]的子类.接受[code]request[/code]和[code]context_processors[/code] ,从而将上下文填充渲染到模板问题已经很明确,由于使用了[code]render_to_response[/code]方法,没有手动添加[code]context_instance=RequestContext(request)[/code]导致模板不能使用[code]{{ perms }}[/code]变量 [b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部