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


当前回答

下面这些可以获得完整的url和部分url:

def myview(request):
    request.build_absolute_uri()
    # http://localhost:8000/admin/store/product/

    request.build_absolute_uri('/')
    # http://localhost:8000/

    request.build_absolute_uri('/')[:-1]
    # http://localhost:8000

    request.scheme
    # http

    request.META['HTTP_HOST']
    # localhost:8000

    request.path    
    # /admin/store/product/

其他回答

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

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

如果您想要实际的HTTP Host报头,请参阅Daniel Roseman对@Phsiao的回答的评论。另一种选择是使用contrib。sites框架,你可以在数据库中为站点设置一个规范的域名(将请求域映射到一个具有正确SITE_ID的设置文件是你必须通过你的webserver设置自己做的事情)。在这种情况下,你要寻找:

from django.contrib.sites.models import Site

current_site = Site.objects.get_current()
current_site.domain

如果您想使用current_site对象,则必须自己将其放入模板上下文中。如果你到处都在使用它,你可以把它打包到一个模板上下文处理器中。

我认为我们想要的是现有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...

下面这些可以获得完整的url和部分url:

def myview(request):
    request.build_absolute_uri()
    # http://localhost:8000/admin/store/product/

    request.build_absolute_uri('/')
    # http://localhost:8000/

    request.build_absolute_uri('/')[:-1]
    # http://localhost:8000

    request.scheme
    # http

    request.META['HTTP_HOST']
    # localhost:8000

    request.path    
    # /admin/store/product/