我怎么能得到完整/绝对的URL(例如https://example.com/some/path)在Django没有网站模块?这太愚蠢了……我不需要查询我的数据库来抓取URL!

我想使用reverse()。


当前回答

如果你不想访问数据库,你可以通过设置来实现。然后,使用上下文处理器将其添加到每个模板:

# settings.py (Django < 1.9)
...
BASE_URL = 'http://example.com'
TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'myapp.context_processors.extra_context',
)
# settings.py (Django >= 1.9)
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # Additional
                'myapp.context_processors.extra_context',
            ],
        },
    },
]

# myapp/context_processors.py
from django.conf import settings

def extra_context(request):
    return {'base_url': settings.BASE_URL}

# my_template.html
<p>Base url is {{ base_url }}.</p>

其他回答

我明白了:

wsgiref.util.request_uri(request.META)

获取包含模式、主机、端口路径和查询的完整uri。

Request.get_host()将为您提供域。

你可以传递request reverse('view-name', request=request)或者用build_absolute_uri将reverse()包含进来request.build_absolute_uri(reverse('view-name'))

如果你使用的是django REST框架,你可以使用rest_framework.reverse中的反向函数。这与django.core.urlresolvers的行为相同。相反,除了它使用一个请求参数来构建一个完整的URL。

from rest_framework.reverse import reverse

# returns the full url
url = reverse('view_name', args=(obj.pk,), request=request)

# returns only the relative url
url = reverse('view_name', args=(obj.pk,))

经过编辑,只提到REST框架中的可用性

django-fullurl

如果你想在Django模板中这样做,我已经发布了一个小的PyPI包Django -fullurl,让你用fullurl和fullstatic替换url和静态模板标签,就像这样:

{% load fullurl %}

Absolute URL is: {% fullurl "foo:bar" %}

Another absolute URL is: {% fullstatic "kitten.jpg" %}

这些徽章应该自动保持最新:

在视图中,当然可以使用request。build_absolute_uri代替。