如何从django视图中的绝对url获取相对url ?

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

Is there a handy function that converts absolute url to relative url in django?
Preferably, it would return the absolute url if base url doesn't actually match.

在django中是否有一个方便的函数将绝对url转换为相对url ?最好是,如果基本url实际上不匹配,它将返回绝对url。

1 个解决方案

#1


1  

You can use urlparse to get the relative path from the absolute uri. The following snippet is using urlparse from six so that it works both under PY2 and PY3.

可以使用urlparse从绝对uri获取相对路径。下面的代码片段使用了来自6的urlparse,以便它在PY2和PY3下都能工作。

def get_relative_url(absolute_uri):
    from six.moves.urllib.parse import urlparse
    return urlparse(absolute_uri).path

#1


1  

You can use urlparse to get the relative path from the absolute uri. The following snippet is using urlparse from six so that it works both under PY2 and PY3.

可以使用urlparse从绝对uri获取相对路径。下面的代码片段使用了来自6的urlparse,以便它在PY2和PY3下都能工作。

def get_relative_url(absolute_uri):
    from six.moves.urllib.parse import urlparse
    return urlparse(absolute_uri).path