
正文
Django将request对象传入模板配置
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
对于很多时候,需要从模板中获取很请求中很多内容,比如当前请求的url,当前的session变量中的某个值,这时候我们可以通过配置可将request对象传递进模板。
django1.10版本:
settings.py
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.request', ... ], }, },]
添加:
TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.request",)
django1.11版本:
只需在setting.py的TEMPLATES中添加django.template.context_processors.request
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.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', ], }, },]
模板中获取某个request值
#获取session中某个值{{ request.session.username }}#获取当然请求的url{{ request.path }}






