99热99这里只有精品6国产,亚洲中文字幕在线天天更新,在线观看亚洲精品国产福利片 ,久久久久综合网

歡迎加入QQ討論群258996829
麥子學(xué)院 頭像
蘋果6袋
6
麥子學(xué)院

Django模板無法使用perms變量問題如何解決?

發(fā)布時(shí)間:2017-09-10 22:52  回復(fù):0  查看:2144   最后回復(fù):2017-09-10 22:52  

本文和大家分享的主要是Django模板無法使用perms變量問題相關(guān)內(nèi)容,一起來看看吧,希望對(duì)大家學(xué)習(xí)django有所幫助。

  首先,在使用Django內(nèi)置權(quán)限管理系統(tǒng)時(shí),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',

  ],

  },

  },

  ]

  如何在模板進(jìn)行權(quán)限檢查呢?

  根據(jù)官網(wǎng)說明 ,已登錄用戶權(quán)限保存在模板{{ perms }}變量中,是權(quán)限模板代理django.contrib.auth.context_processors.PermWrapper的一個(gè)實(shí)例,

  具體可以查看django/contrib/auth/context_processors.py源碼

  測試用例:

Django模板無法使用perms變量問題如何解決?

  測試過程中,發(fā)現(xiàn){{ 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),

  }

  測試訪問接口,發(fā)現(xiàn)有的接口有打印權(quán)限信息,有的沒有,似乎恍然醒悟

  可以打印權(quán)限信息的接口返回:

  return render(request, 'fms/fms_add.html', {'request': request, 'form': form, 'error': error})

  不能打印權(quán)限新的接口返回:

  return render_to_response( 'fms/fms.html', data)

  renderrender_to_response區(qū)別

  render是比render_to_reponse更便捷渲染模板的方法,會(huì)自動(dòng)使用RequestContext,而后者需要手動(dòng)添加:

  return render_to_response(request, 'fms/fms_add.html', {'request': request, 'form': form, 'error': error},context_instance=RequestContext(request))

  其中RequestContextdjango.template.Context的子類.接受requestcontext_processors,從而將上下文填充渲染到模板

  問題已經(jīng)很明確,由于使用了render_to_response方法,沒有手動(dòng)添加context_instance=RequestContext(request)導(dǎo)致模板不能使用{{ perms }}變量

 

 

來源:Geekwolf's Blog

您還未登錄,請(qǐng)先登錄

熱門帖子

最新帖子

?