首页 > 解决方案 > Django 绝对网址

问题描述

所以我是 django 的新手 我一直在研究 PHP CodeIgniter 在其中将绝对 URL 放入 href 我使用了一个base_url通过调用 URL helper 调用的函数

<?php echo base_url().'user/login';?>


它给出的输出类似于
http://localhost/projectname/user/login
我在 Django 中想要同样的东西,但没有得到任何我能理解的答案或答案。我不想使用相对 URL,我的预期结果应该是这样的

{% url 'login' %}


上面的代码应该返回
http://localhost/projectname/user/login

标签: pythondjangocodeigniterurl

解决方案


您可以在 django 中通过 2 种方式获取绝对 url。

一种是使用 HttpRequest.build_absolute_uri()HttpRequest 中的方法构建您的自定义模板标签

或者只是在您的 django 模板中使用以下行。

<a href="{{ request.get_host }}{% url your_url_name %}">Link</a>

有关详细信息,请参阅此链接: https ://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.get_host


推荐阅读