我怎么能得到完整/绝对的URL(例如https://example.com/some/path)在Django没有网站模块?这太愚蠢了……我不需要查询我的数据库来抓取URL!
我想使用reverse()。
我怎么能得到完整/绝对的URL(例如https://example.com/some/path)在Django没有网站模块?这太愚蠢了……我不需要查询我的数据库来抓取URL!
我想使用reverse()。
当前回答
我使用这个代码:
request.build_absolute_uri('/')[:-1]
回应:
https://yourdomain.com
其他回答
我明白了:
wsgiref.util.request_uri(request.META)
获取包含模式、主机、端口路径和查询的完整uri。
我使用这个代码:
request.build_absolute_uri('/')[:-1]
回应:
https://yourdomain.com
我遇到这个线程是因为我正在寻找为成功页面构建一个绝对URI。request.build_absolute_uri()给了我当前视图的URI,但为了获得我的成功视图的URI,我使用了以下....
request.build_absolute_uri(反向(success_view_name))
检查请求。META字典。我认为它有服务器名和服务器端口。
如果你不想访问数据库,你可以通过设置来实现。然后,使用上下文处理器将其添加到每个模板:
# 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>