Django:在模板中获取当前url信息
确保项目配置里的context_processors
包含django.template.context_processors.request
.
从 Django 1.9 开始, 默认是已经配置的。
Python
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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/Jinja
{{ request.path }}
获取带有querystring的URL:
Django/Jinja
{{ request.get_full_path }}
获取完全的绝对路径:
Django/Jinja
{{ request.build_absolute_uri }}
示例表
假设, 我们的URL是: https://jackeygao.io/search/?keyword=django
Method |
Output |
---|---|
request.path |
/search/ |
request.get_full_path |
search/?keyword=django |
request.build_absolute_uri |
https://jackeygao.io/search/?keyword=django |
Django 1.7 或者更早的版本
settings.py
Raw
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
TEMPLATE_CONTEXT_PROCESSORS = TCP + (
'django.core.context_processors.request',
)