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


当前回答

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

其他回答

from django.contrib.sites.models import Site
if Site._meta.installed:
    site = Site.objects.get_current()
else:
    site = RequestSite(request)

我知道这个问题很老了,但我是在寻找一种python方法来获取当前域时偶然发现的。

def myview(request):
    domain = request.build_absolute_uri('/')[:-1]
    # that will build the complete domain: http://foobar.com

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

(概览)

    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的答案

补充Carl Meyer,你可以做一个这样的上下文处理器:

module.context_processors.py

from django.conf import settings

def site(request):
    return {'SITE_URL': settings.SITE_URL}

当地settings.py

SITE_URL = 'http://google.com' # this will reduce the Sites framework db call.

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "module.context_processors.site",
    ....
 )

返回上下文实例的模板,url站点为{{SITE_URL}}

如果想在上下文处理器中处理子域或SSL,可以编写自己的例程。

类似于用户panchicore的回复,这是我在一个非常简单的网站上所做的。 它提供了一些变量,并使它们在模板中可用。

SITE_URL将保存类似example.com的值 SITE_PROTOCOL将保存类似http或https的值 SITE_PROTOCOL_URL将包含http://example.com或https://example.com这样的值 SITE_PROTOCOL_RELATIVE_URL将包含类似//example.com的值。

模块/ context_processors.py

from django.conf import settings

def site(request):

    SITE_PROTOCOL_RELATIVE_URL = '//' + settings.SITE_URL

    SITE_PROTOCOL = 'http'
    if request.is_secure():
        SITE_PROTOCOL = 'https'

    SITE_PROTOCOL_URL = SITE_PROTOCOL + '://' + settings.SITE_URL

    return {
        'SITE_URL': settings.SITE_URL,
        'SITE_PROTOCOL': SITE_PROTOCOL,
        'SITE_PROTOCOL_URL': SITE_PROTOCOL_URL,
        'SITE_PROTOCOL_RELATIVE_URL': SITE_PROTOCOL_RELATIVE_URL
    }

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "module.context_processors.site",
    ....
 )

SITE_URL = 'example.com'

然后,在你的模板上,使用它们作为{{SITE_URL}}, {{SITE_PROTOCOL}}, {{SITE_PROTOCOL_URL}}和{{SITE_PROTOCOL_RELATIVE_URL}}