国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

解決Django模板無法使用perms變量問題的方法

2020-02-16 10:12:14
字體:
來源:轉載
供稿:網友

前言

本文主要給大家介紹了關于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是

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南皮县| 广元市| 禄丰县| 库伦旗| 沿河| 二手房| 临邑县| 大悟县| 沙洋县| 司法| 团风县| 赤城县| 怀远县| 赤峰市| 鹿泉市| 株洲县| 巴东县| 韶山市| 银川市| 上杭县| 垣曲县| 海盐县| 杂多县| 宣汉县| 马边| 塔河县| 英吉沙县| 穆棱市| 寿光市| 蕉岭县| 沾益县| 贵定县| 昂仁县| 平定县| 德昌县| 德清县| 新余市| 喀喇| 鄂尔多斯市| 太原市| 彭泽县|