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

我想使用reverse()。


当前回答

我遇到这个线程是因为我正在寻找为成功页面构建一个绝对URI。request.build_absolute_uri()给了我当前视图的URI,但为了获得我的成功视图的URI,我使用了以下....

request.build_absolute_uri(反向(success_view_name))

其他回答

还有另一种方式。您可以在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 }}
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]
<div class='col-12 col-md-6'>
    <p class='lead'>Login</p>
    {% include 'accounts/snippets/form.html' with form=login_form next_url=request.build_absolute_uri %}
</div>

例如,在这里,我说加载表单,并告诉表单,下一个URL是当前的URL,这段代码呈现

要从模板创建到另一个页面的完整链接,您可以使用以下命令:

{{ request.META.HTTP_HOST }}{% url 'views.my_view' my_arg %}

request.META。HTTP_HOST给出主机名,url给出相对名。然后模板引擎将它们连接成一个完整的url。

检查请求。META字典。我认为它有服务器名和服务器端口。