如何从Django模板中获取当前站点的域名?我试着在标签和过滤器中寻找,但没有什么。


当前回答

我认为你想要的是访问请求上下文,参见RequestContext。

其他回答

在Django模板中,你可以这样做:

<a href="{{ request.scheme }}://{{ request.META.HTTP_HOST }}{{ request.path }}?{{ request.GET.urlencode }}" >link</a>

我发现了{{请求。Get_host}}方法。

正如@furins的回复中提到的,代理服务器可能存在问题。我在使用Apache和uWSGI - request时发现了这一点。Get_host或request。Build_absolute_uri将返回代理主机(127.0.0.1:9191…)。

然而,有人已经发布了一个有用的指南来解决这个问题:

https://ubuntu.com/blog/django-behind-a-proxy-fixing-absolute-urls

虽然这是一个相对较老的答案,但它仍然与django 3.2和python 3.9相关。

为了防止这个答案在未来消失,以下是它的要点:

settings.py

# Setup support for proxy headers
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

apache.conf

<VirtualHost *:443>
    ...
    RequestHeader set X-Forwarded-Proto 'https' env=HTTPS

    ProxyPass / http://10.0.0.3/
    ProxyPassReverse / http://10.0.0.3/
    ...
</VirtualHost>

使用这些设置请求。Get_host和request。Build_absolute_uri引用客户端请求的主机,而不是代理主机。

我使用自定义模板标记。例如:<your_app>/templatetags/site.py:

# -*- coding: utf-8 -*-
from django import template
from django.contrib.sites.models import Site

register = template.Library()

@register.simple_tag
def current_domain():
    return 'http://%s' % Site.objects.get_current().domain

在模板中使用它,就像这样:

{% load site %}
{% current_domain %}

快速简单,但不适合生产:

(概览)

    request.scheme               # http or https
    request.META['HTTP_HOST']    # example.com
    request.path                 # /some/content/1/

(在模板中)

{{ request.scheme }} :// {{ request.META.HTTP_HOST }} {{ request.path }}

确保使用RequestContext,如果你使用渲染就是这样。

不要相信请求。生产中的META['HTTP_HOST']:该信息来自浏览器。相反,请使用@CarlMeyer的答案