如何从Django模板中获取当前站点的域名?我试着在标签和过滤器中寻找,但没有什么。
当前回答
我认为你想要的是访问请求上下文,参见RequestContext。
其他回答
{{请求。get_host}}在和ALLOWED_HOSTS设置(在Django 1.4.4中添加)一起使用时,可以防止HTTP主机头攻击。
注意{{request.META。HTTP_HOST}}没有相同的保护。查看文档:
ALLOWED_HOSTS A list of strings representing the host/domain names that this Django site can serve. This is a security measure to prevent HTTP Host header attacks, which are possible even under many seemingly-safe web server configurations. ... If the Host header (or X-Forwarded-Host if USE_X_FORWARDED_HOST is enabled) does not match any value in this list, the django.http.HttpRequest.get_host() method will raise SuspiciousOperation. ... This validation only applies via get_host(); if your code accesses the Host header directly from request.META you are bypassing this security protection.
至于在模板中使用请求,在Django 1.8中,模板渲染函数调用已经改变了,所以你不再需要直接处理RequestContext。
下面是如何渲染视图的模板,使用快捷函数render():
from django.shortcuts import render
def my_view(request):
...
return render(request, 'my_template.html', context)
下面是如何呈现一个电子邮件模板,IMO是更常见的情况下,你想要的主机值:
from django.template.loader import render_to_string
def my_view(request):
...
email_body = render_to_string(
'my_template.txt', context, request=request)
下面是一个在电子邮件模板中添加完整URL的示例;请求。Scheme应该获得HTTP或HTTPS,这取决于您使用的是什么:
Thanks for registering! Here's your activation link:
{{ request.scheme }}://{{ request.get_host }}{% url 'registration_activate' activation_key %}
这种方法怎么样?对我有用。 它也用于django注册。
def get_request_root_url(self):
scheme = 'https' if self.request.is_secure() else 'http'
site = get_current_site(self.request)
return '%s://%s' % (scheme, site)
我发现了{{请求。Get_host}}方法。
你可以使用request.build_absolute_uri()
默认情况下,它将返回一个完整的路径。
但是如果你传入一个像这样的参数:
request.build_absolute_uri('/')
这将返回域名。
我认为你想要的是访问请求上下文,参见RequestContext。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何在django应用程序中显示favicon ?
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if