我怎么能得到完整/绝对的URL(例如https://example.com/some/path)在Django没有网站模块?这太愚蠢了……我不需要查询我的数据库来抓取URL!
我想使用reverse()。
我怎么能得到完整/绝对的URL(例如https://example.com/some/path)在Django没有网站模块?这太愚蠢了……我不需要查询我的数据库来抓取URL!
我想使用reverse()。
当前回答
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.META.HTTP_HOST }}{% url 'views.my_view' my_arg %}
request.META。HTTP_HOST给出主机名,url给出相对名。然后模板引擎将它们连接成一个完整的url。
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代替。
如果你不想访问数据库,你可以通过设置来实现。然后,使用上下文处理器将其添加到每个模板:
# 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>
还有ABSOLUTE_URL_OVERRIDES可用作为设置
https://docs.djangoproject.com/en/2.1/ref/settings/#absolute-url-overrides
但这将覆盖get_absolute_url(),这可能是不可取的。
我认为更好的解决方案是把它放在models.py中,而不是仅仅为此安装sites框架,或者做一些这里提到的依赖于request对象的其他事情
在settings.py中定义BASE_URL,然后将其导入models.py并创建一个抽象类(或将其添加到您已经在使用的类中),该类定义get_truly_absolute_url()。它可以很简单:
def get_truly_absolute_url(self):
return BASE_URL + self.get_absolute_url()
子类化它,现在你可以在任何地方使用它。
你还可以使用:
import socket
socket.gethostname()
这对我来说很好,
我不太清楚它是怎么运作的。我相信这是更低级的,它将返回您的服务器主机名,这可能与您的用户访问您的页面所使用的主机名不同。