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

我想使用reverse()。


当前回答

在做一个项目的时候,我学会了在Django中获取完整/绝对的URL。

如果你的URL在地址栏中是这样的:

https://stackoverflow.com/questions/2345708

如果你想把上面的URL显示给你的模板。

{{请求。不带GET参数。 {{请求。get_full_path}} #带有GET参数

对于上面的两个代码,这将打印在你的模板中

questions/2345708

另一种获取完整URL的方法是:

{{request.build_absolute_uri}}

这将打印在你的模板将是:

https://stackoverflow.com/questions/2345708

其他回答

不是绝对的url,但我正在寻找只是得到主机。如果你想在view.py中获得host,你可以这样做

def my_view(request):
   host = f"{ request.scheme }://{ request.META.get('HTTP_HOST') }"

还有另一种方式。您可以在view.py中使用build_absolute_uri()并将其传递给模板。

view.py

def index(request):
    baseurl = request.build_absolute_uri()
    return render_to_response('your-template.html', { 'baseurl': baseurl })

your-template.html

{{ baseurl }}
request.get_host()

在django中使用这个请求对象

这在我的模板中很管用:

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