Python 如何在django模板中获取基本url
给定一个网站,您如何在django模板中获得该网站的主机,而不从视图中传递该varPython 如何在django模板中获取基本url,python,django,Python,Django,给定一个网站,您如何在django模板中获得该网站的主机,而不从视图中传递该var http://google.com/hello --> {{ BASE_URL }} ==> 'http://google.com' 通过在设置中添加以下templact\u CONTEXT\u PROCESSOR中间件,可以在模板中获取request对象: TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.req
http://google.com/hello --> {{ BASE_URL }} ==> 'http://google.com'
通过在设置中添加以下
templact\u CONTEXT\u PROCESSOR
中间件,可以在模板中获取request
对象:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
上面有一些。然后,您可以调用您的模板:
{{ request.META.HTTP_NAME }}
这将为您提供基本url。这一点在下文中得到了广泛的回答 有几种方法可以做到这一点:
**请注意,可以在模板中对这些内容进行欺骗,以获取基本url
{{ request.get_host }}
URL:
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_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.scheme }}://{{ request.get_host }}
感谢您提供全面的答案/选项。能否请您补充一下前两个如何被欺骗?前两个取决于请求元数据,它基本上来自浏览器。这可以通过“允许的主机”设置来解决,在这里可以找到更多信息