dot*_*tty 290 django django-templates
我想知道如何在模板中获取当前的URL.
说我的网址是
.../user/profile/
Run Code Online (Sandbox Code Playgroud)
如何将其返回到模板?
Red*_*yph 279
您可以像这样在模板中获取网址:
<p>URL of this page: {{ request.get_full_path }}</p>
Run Code Online (Sandbox Code Playgroud)
或者
{{ request.path }}
如果你不需要额外的参数.
应该对hypete和Igancio的答案进行一些精确和更正,我将在这里总结一下整个想法,以供将来参考.
如果您需要request
模板中的变量,则必须将"django.core.context_processors.request"添加到TEMPLATE_CONTEXT_PROCESSORS
设置中,默认情况下不是这样(Django 1.4).
您还必须忘记应用程序使用的其他上下文处理器.因此,要将请求添加到其他默认处理器,您可以在设置中添加此请求,以避免硬编码默认处理器列表(在以后的版本中可能会更改):
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
TEMPLATE_CONTEXT_PROCESSORS = TCP + (
'django.core.context_processors.request',
)
Run Code Online (Sandbox Code Playgroud)
然后,只要您在回复中发送request
内容,例如:
from django.shortcuts import render_to_response
from django.template import RequestContext
def index(request):
return render_to_response(
'user/profile.html',
{ 'title': 'User profile' },
context_instance=RequestContext(request)
)
Run Code Online (Sandbox Code Playgroud)
htt*_*ete 200
Django 1.9及以上版本:
## template
{{ request.path }} # -without GET parameters
{{ request.get_full_path }} # - with GET parameters
Run Code Online (Sandbox Code Playgroud)
旧:
## settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
## views.py
from django.template import *
def home(request):
return render_to_response('home.html', {}, context_instance=RequestContext(request))
## template
{{ request.path }}
Run Code Online (Sandbox Code Playgroud)
小智 21
下面的代码帮助我:
{{ request.build_absolute_uri }}
Run Code Online (Sandbox Code Playgroud)
两者都{{ request.path }} and {{ request.get_full_path }}
返回当前 URL 但不返回绝对 URL,例如:
your_website.com/wallpapers/new_wallpaper
两者都会返回
/new_wallpaper/
(注意开头和结尾的斜杠)
所以你必须做类似的事情
{% if request.path == '/new_wallpaper/' %}
<button>show this button only if url is new_wallpaper</button>
{% endif %}
Run Code Online (Sandbox Code Playgroud)
但是,您可以使用(感谢上面的答案)获取绝对 URL
{{ request.build_absolute_uri }}
Run Code Online (Sandbox Code Playgroud)
注意:您不必包含request
在 中settings.py
,它已经存在。
在django模板中,
只需获取当前URL {{request.path}}
以获取带参数的完整URL{{request.get_full_path}}
注意:您必须添加request
djangoTEMPLATE_CONTEXT_PROCESSORS
我想发送到模板的完整请求有点多余.我是这样做的
def home(request):
app_url = request.path
return render(request, 'home.html', {'app_url': app_url})
##template
{{ app_url }}
Run Code Online (Sandbox Code Playgroud)