如何在django模板中将名称反转为绝对URL?

时间:2022-09-04 12:07:56

{% url url_name %} gives a relative name.

{%url url_name%}给出相对名称。

How can I do something like {% absolute_url url_name %} so that it returns url with base (including port if present)?

如何执行{%absolute_url url_name%}之类的操作,以便它返回带有base的url(包括端口,如果存在)?

3 个解决方案

#1


21  

There are different solutions. Write your own templatetag and use HttpRequest.build_absolute_uri(location). But another way, and a bit hacky.

有不同的解决方案。编写自己的模板标签并使用HttpRequest.build_absolute_uri(位置)。但另一种方式,有点hacky。

<a href="{{ request.get_host }}{% url url_name %}">click here</a>

#2


9  

You can use the build_absolute_uri() method in the request object. In template use this as request.build_absolute_uri. This will create the absolute address including protocol, host and port.

您可以在请求对象中使用build_absolute_uri()方法。在模板中使用它作为request.build_absolute_uri。这将创建包括协议,主机和端口的绝对地址。

Example:

例:

 <a href="{{request.build_absolute_uri}}">click here</a>

#3


7  

In template I use this to print absolute URL with protocol, host and port if present:

在模板中,我使用它来打印带有协议,主机和端口的绝对URL(如果存在):

<a href="{{ request.scheme }}://{{ request.get_host }}{% url url_name %}">link</a>

In Python I use:

在Python中我使用:

from django.core.urlresolvers import reverse

def do_something(request):
    link = "{}://{}{}".format(request.scheme, request.get_host(), reverse('url_name', args=(some_arg1,)))

#1


21  

There are different solutions. Write your own templatetag and use HttpRequest.build_absolute_uri(location). But another way, and a bit hacky.

有不同的解决方案。编写自己的模板标签并使用HttpRequest.build_absolute_uri(位置)。但另一种方式,有点hacky。

<a href="{{ request.get_host }}{% url url_name %}">click here</a>

#2


9  

You can use the build_absolute_uri() method in the request object. In template use this as request.build_absolute_uri. This will create the absolute address including protocol, host and port.

您可以在请求对象中使用build_absolute_uri()方法。在模板中使用它作为request.build_absolute_uri。这将创建包括协议,主机和端口的绝对地址。

Example:

例:

 <a href="{{request.build_absolute_uri}}">click here</a>

#3


7  

In template I use this to print absolute URL with protocol, host and port if present:

在模板中,我使用它来打印带有协议,主机和端口的绝对URL(如果存在):

<a href="{{ request.scheme }}://{{ request.get_host }}{% url url_name %}">link</a>

In Python I use:

在Python中我使用:

from django.core.urlresolvers import reverse

def do_something(request):
    link = "{}://{}{}".format(request.scheme, request.get_host(), reverse('url_name', args=(some_arg1,)))