【发布时间】:2015-04-21 10:35:46
【问题描述】:
给定一个网站,如何在 django 模板中获取该网站的 HOST,而不从视图中传递该 var?
http://google.com/hello --> {{ BASE_URL }} ==> 'http://google.com'
【问题讨论】:
给定一个网站,如何在 django 模板中获取该网站的 HOST,而不从视图中传递该 var?
http://google.com/hello --> {{ BASE_URL }} ==> 'http://google.com'
【问题讨论】:
这些其他答案都没有考虑到方案。这对我有用:
{{ request.scheme }}://{{ request.get_host }}
【讨论】:
网址:google.com/hello
在模板中:
{{ request.get_full_path() }}
return /hello
OR
{{ request.get_host() }}
return google.com
鉴于:
from django.contrib.sites.shortcuts import get_current_site
def home(request):
get_current_site(request)
# google.com
# OR
request.get_host()
# google.com
# OR
request.get_full_path()
# /hello
【讨论】:
在您的模板中获取基本网址
{{ request.get_host() }}
【讨论】:
这已在以下post中得到了广泛的回答
有几种方法:
{{ request.get_host() }} **contrib.sites 框架** 请注意这些可以被欺骗
【讨论】:
您可以通过在设置中添加以下TEMPLECT_CONTEXT_PROCESSOR 中间件来获取模板中的request 对象:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
这里有一些documentation。然后你可以调用你的模板:
{{ request.META.HTTP_NAME }}
这将为您提供基本网址。
【讨论】: