搜索
首页后端开发Python教程有关Django模板无法使用perms变量问题的解决方法

这篇文章主要给大家介绍了关于解决Django模板无法使用perms变量问题的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

前言

本文主要给大家介绍了关于Django模板无法使用perms变量的解决方法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

解决方法:

首先,在使用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',
   ],
  },
 },
]

如何在模板进行权限检查呢?

根据官网说明 https://docs.djangoproject.com/en/1.11/topics/auth/default/#permissions ,已登录用户权限保存在模板{{ perms }}变量中,是权限模板代理django.contrib.auth.context_processors.PermWrapper的一个实例,具体可以查看django/contrib/auth/context_processors.py源码

测试用例:

 

测试过程中,发现{{ perms }}变量压根不存在,没有任何输出;好吧,只能取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)

render和render_to_response区别

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

以上是有关Django模板无法使用perms变量问题的解决方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python中的合并列表:选择正确的方法Python中的合并列表:选择正确的方法May 14, 2025 am 12:11 AM

Tomergelistsinpython,YouCanusethe操作员,estextMethod,ListComprehension,Oritertools

如何在Python 3中加入两个列表?如何在Python 3中加入两个列表?May 14, 2025 am 12:09 AM

在Python3中,可以通过多种方法连接两个列表:1)使用 运算符,适用于小列表,但对大列表效率低;2)使用extend方法,适用于大列表,内存效率高,但会修改原列表;3)使用*运算符,适用于合并多个列表,不修改原列表;4)使用itertools.chain,适用于大数据集,内存效率高。

Python串联列表字符串Python串联列表字符串May 14, 2025 am 12:08 AM

使用join()方法是Python中从列表连接字符串最有效的方法。1)使用join()方法高效且易读。2)循环使用 运算符对大列表效率低。3)列表推导式与join()结合适用于需要转换的场景。4)reduce()方法适用于其他类型归约,但对字符串连接效率低。完整句子结束。

Python执行,那是什么?Python执行,那是什么?May 14, 2025 am 12:06 AM

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python:关键功能是什么Python:关键功能是什么May 14, 2025 am 12:02 AM

Python的关键特性包括:1.语法简洁易懂,适合初学者;2.动态类型系统,提高开发速度;3.丰富的标准库,支持多种任务;4.强大的社区和生态系统,提供广泛支持;5.解释性,适合脚本和快速原型开发;6.多范式支持,适用于各种编程风格。

Python:编译器还是解释器?Python:编译器还是解释器?May 13, 2025 am 12:10 AM

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

python用于循环与循环时:何时使用哪个?python用于循环与循环时:何时使用哪个?May 13, 2025 am 12:07 AM

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

Python循环:最常见的错误Python循环:最常见的错误May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!