我怎么能得到完整/绝对的URL(例如https://example.com/some/path)在Django没有网站模块?这太愚蠢了……我不需要查询我的数据库来抓取URL!
我想使用reverse()。
我怎么能得到完整/绝对的URL(例如https://example.com/some/path)在Django没有网站模块?这太愚蠢了……我不需要查询我的数据库来抓取URL!
我想使用reverse()。
当前回答
要从模板创建到另一个页面的完整链接,您可以使用以下命令:
{{ request.META.HTTP_HOST }}{% url 'views.my_view' my_arg %}
request.META。HTTP_HOST给出主机名,url给出相对名。然后模板引擎将它们连接成一个完整的url。
其他回答
在做一个项目的时候,我学会了在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
在请求时使用方便的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.get_full_path()"
如果你想使用reverse(),你可以这样做:request。build_absolute_uri(反向(view_name, args = (obj。pk,)))