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


当前回答

正如@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.build_absolute_uri()

默认情况下,它将返回一个完整的路径。

但是如果你传入一个像这样的参数:

request.build_absolute_uri('/')

这将返回域名。

我认为我们想要的是现有url标签的替代品,所以我写了一个新标签:

from django.template import Library
from django.urls     import reverse

@register.simple_tag(takes_context = True)
def fullURL(context, name, *args, **kwargs):
    request = context['request']
    return f'{request.scheme}://{request.get_host()}{reverse(name, args = args, kwargs = kwargs)}'

然后在你的模板中你可以这样…

{% extends "myapp/email/email_base.html" %}

{% load mytags %} {# Replace mytags with whatever the name of your custom tags calss is. #}

{% block content %}
<p>You can use <a href="{% fullURL 'signup' %}">this link</a> to get started with your account. We look forward to seeing you soon!</p>
{% endblock content %}

然后,当你生成这个时,你只需要记住将请求传递到上下文,就像这样……

from django.template.loader import render_to_string

def sendEmail(subject, to, template, **context):
    html = render_to_string(f'myapp/email/{template}.html', context | {'subject': subject})
    # ... and so on with the rest of my function for sending email...

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

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

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