国产探花免费观看_亚洲丰满少妇自慰呻吟_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是

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 奉新县| 汤原县| 威海市| 盐池县| 钟祥市| 当雄县| 翁源县| 灌云县| 石家庄市| 富民县| 青海省| 肇庆市| 宜春市| 浦县| 吴桥县| 集贤县| 汶上县| 应城市| 文水县| 申扎县| 富阳市| 明星| 巴东县| 温宿县| 湘阴县| 香河县| 肇东市| 县级市| 卫辉市| 衡阳市| 云和县| 大田县| 横山县| 长沙县| 商洛市| 临桂县| 延边| 东阿县| 唐山市| 类乌齐县| 社会|