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

首頁 > 編程 > Python > 正文

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

2020-01-04 16:42:54
字體:
來源:轉載
供稿:網友

前言

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

測試用例:

django,模板變量,模板,變量賦值,模板設置變量

測試過程中,發現{{ 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 }}變量

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 鞍山市| 万盛区| 湛江市| 大渡口区| 高清| 西城区| 休宁县| 沁阳市| 津南区| 瑞金市| 纳雍县| 常熟市| 双牌县| 玛多县| 页游| 沂水县| 遂昌县| 临西县| 会昌县| 普宁市| 德惠市| 陆良县| 盘锦市| 五原县| 晴隆县| 玉林市| 化州市| 南漳县| 江口县| 靖州| 夏河县| 天祝| 财经| 昭通市| 宁陵县| 额尔古纳市| 泸州市| 裕民县| 集安市| 海城市| 河津市|