61

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

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

4

7 回答 7

74

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

def get_current_path(request):
    return {
       'current_path': request.get_full_path()
     }

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

{{ current_path }}

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

看:

于 2010-07-14T17:44:57.487 回答
24

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

TEMPLATE_CONTEXT_PROCESSORS = (

    # Put your context processors here

    'django.core.context_processors.request',
)

在模板使用中:

{{ request.get_full_path }}

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

于 2014-01-25T11:38:17.187 回答
9

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

def myurl( request ):
  return { 'myurlx': request.get_full_path() }

在 settings.py 中:

TEMPLATE_CONTEXT_PROCESSORS = (
  ...
  wherever_it_is.context_processors.myurl,
  ...

在您的 template.html 中:

myurl={{myurlx}}
于 2010-07-14T17:44:41.010 回答
4

如果我们访问以下 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'
于 2021-02-19T08:49:44.690 回答
2

除了 sdolan 的回答:

如果您正在使用 I18N 并希望将next值传递给以/i18n/setlang/更改当前页面的语言,那么您也需要从完整路径中删除当前语言代码。就像是:

full_path = request.get_full_path()
current_path = full_path[full_path.index('/', 1):]

这假设每条路径都有格式/LANG_CODE/any/other/stuff/with/?param='yay'并且简单地开始LANG_CODE它是什么(例如,/en/将导致/)。

于 2014-01-19T16:26:56.230 回答
2

您可以查看您的网址是否与其他网址不同。

{% if 'foo/bar/' in request.get_full_path %}
于 2017-05-19T18:42:32.710 回答
1

Django 有很多内置的东西,但是如果你不明确你想使用什么,它就不会被使用。

因此,在 MTV 模式(模型、模板、视图)中,视图接收请求并使用模板渲染生成响应,向其传递该视图的字典或所有局部变量(使用 locals() 函数)。知道了这一点,我们可以插入来自响应的当前 url,如下所示:

视图.py:

from django.shortcuts import render

def page(request):
    currentUrl = request.get_full_path()
    return render(request, 'app/page.html', locals())

然后,在模板 'app/page.html' 中,您只需执行以下操作即可显示我们刚刚创建并通过 locals() 传递的 currentUrl 变量:

应用程序/模板/page.html:

{{ currentUrl }}
于 2011-11-30T03:59:41.073 回答