Django


1604 浏览 5 years, 11 months

8 Request

版权声明: 转载请注明出处 http://www.codingsoho.com/
Django获取当前页面URL
url = request.META['HTTP_HOST'] + request.META['PATH_INFO'] + request.META['QUERY_STRING']

以下面网址为例

http://127.0.0.1:8001/about/?q=1

主机 路径 Query字符串
request.META['HTTP_HOST'] request.META['PATH_INFO'] request.META['QUERY_STRING']
http://127.0.0.1:8001 /about/ q=1

但更好的方法是通过 request.build_absolute_uri 方法得到

FULL_URL_WITH_QUERY_STRINg FULL_URL ABSOLUTE_ROOT ABSOLUTE_ROOT_URL
request.build_absolute_uri() request.build_absolute_uri('?') request.build_absolute_uri('/')[:-1].strip("/") request.build_absolute_uri('/').strip("/")
http://127.0.0.1:8001/about/?q=1 http://127.0.0.1:8001/about/ http://127.0.0.1:8001 http://127.0.0.1:8001

其他的获取URL的方法

获取带参数URL 获取不带参数URL 获取主机地址
request.get_full_path() request.path request.get_host()
/about/?q=1 /about/ 127.0.0.1:8001

获取完整的带域名可以用request.META.get('HTTP_REFERER')或者django.contrib.sites.get_current_site(request)