Django:在模板中获取当前页面的URL,包括参数

Mat*_*pel 57 django django-templates django-urls

有没有办法在Django模板中获取当前页面URL及其所有参数?

例如,一个可以打印完整URL的模板标签 /foo/bar?param=1&baz=2

Sam*_*lan 71

编写自定义上下文处理器.例如

def get_current_path(request):
    return {
       'current_path': request.get_full_path()
     }
Run Code Online (Sandbox Code Playgroud)

在您的TEMPLATE_CONTEXT_PROCESSORS设置变量中添加该函数的路径,并在模板中使用它,如下所示:

{{ current_path }}
Run Code Online (Sandbox Code Playgroud)

如果要request在每个请求中包含完整对象,可以使用内置django.core.context_processors.request上下文处理器,然后{{ request.get_full_path }}在模板中使用.

看到:

  • 不要忘记使用urlencode即`{{request.get_full_path | urlencode}}`如果你需要这个用于重定向 (4认同)

Mar*_*mro 23

在上下文处理器中使用Django的构建来获取模板上下文中的请求.在设置中添加request处理器TEMPLATE_CONTEXT_PROCESSORS

TEMPLATE_CONTEXT_PROCESSORS = (

    # Put your context processors here

    'django.core.context_processors.request',
)
Run Code Online (Sandbox Code Playgroud)

在模板中使用:

{{ request.get_full_path }}
Run Code Online (Sandbox Code Playgroud)

这样您就不需要自己编写任何新代码了.

  • 应该注意的是,使用此方法会覆盖默认的TEMPLATE_CONTEXT_PROCESSORS,因此您必须将这些添加回列表.[文档](https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATE_CONTEXT_PROCESSORS)列出了要包含在列表中的默认值. (3认同)

eru*_*orm 8

在文件context_processors.py(或类似)中:

def myurl( request ):
  return { 'myurlx': request.get_full_path() }
Run Code Online (Sandbox Code Playgroud)

在settings.py中:

TEMPLATE_CONTEXT_PROCESSORS = (
  ...
  wherever_it_is.context_processors.myurl,
  ...
Run Code Online (Sandbox Code Playgroud)

在您的template.html中:

myurl={{myurlx}}
Run Code Online (Sandbox Code Playgroud)


suh*_*lvs 6

如果我们访问以下 URL:http://127.0.0.1:8000/home/?q=test

然后

request.path = '/home/'
request.get_full_path() = '/home/?q=test'
request.build_absolute_uri() = 'http://127.0.0.1:8000/home/?q=test'
Run Code Online (Sandbox Code Playgroud)