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

我想使用reverse()。


当前回答

request.get_host()

在django中使用这个请求对象

其他回答

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代替。

在请求时使用方便的request.build_absolute_uri()方法,将相对url传递给它,它会给你一个完整的url。

默认情况下,返回request.get_full_path()的绝对URL,但您可以将相对URL作为第一个参数传递给它,以将其转换为绝对URL。

>>> request.build_absolute_uri()
'https://example.com/music/bands/the_beatles/?print=true'
>>> request.build_absolute_uri('/bands/?print=true')
'https://example.com/bands/?print=true'
class WalletViewSet(mixins.ListModelMixin, GenericViewSet):
    serializer_class = WalletSerializers
    pagination_class = CustomPaginationInvestment

    def get_queryset(self):

        ######################################################
        print(self.request.build_absolute_uri())
        #####################################################

        wallet, created = Wallet.objects.get_or_create(owner=self.request.user)
        return Wallet.objects.filter(id=wallet.id)

你得到这样的输出

http://localhost:8000/v1/wallet
HTTP GET /v1/wallet 200 [0.03, 127.0.0.1:41608]

这在我的模板中很管用:

{{ request.scheme }}://{{ request.META.HTTP_HOST }}{% url 'equipos:marca_filter' %}

我需要完整的url传递给一个js获取函数。 我希望这对你有帮助。

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

# 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>