我想知道如何在模板中获得当前URL。

假设我当前的URL是:

.../user/profile/

如何将此返回到模板?


当前回答

{{请求。路径}}和{{request。get_full_path}}返回当前URL而不是绝对URL,例如:

your_website.com/wallpapers/new_wallpaper 两者都会返回/new_wallpaper/ (注意前面和后面的斜杠)

所以你得做点什么

{% if request.path == '/new_wallpaper/' %}
    <button>show this button only if url is new_wallpaper</button>
{% endif %}

但是,您可以使用以下方法获得绝对URL(感谢上面的答案)

{{ request.build_absolute_uri }}

注意: 你不需要在settings.py中包含请求,它已经在那里了。

其他回答

如果你也在模板中使用js,你可以这样做: 在你的js

document.addEventListener('DOMContentLoaded', function() {
    ...
    getUrl();
}

function getUrl() {
    let someDiv = document.querySelector(`#someDiv`);
    someDiv.innerHTML = window.location.href;
}

对于你的模板

...
<div id="someDiv"><div>
...

我想发送到模板完整的请求有点多余。我这样做

from django.shortcuts import render

def home(request):
    app_url = request.path
    return render(request, 'home.html', {'app_url': app_url})

##template
{{ app_url }}

下面的代码帮助我:

 {{ request.build_absolute_uri }}

你可以使用{{request.path}}获取不带参数的url。 你可以使用{{request.get_full_path}}来获取带参数的url。

这是一个老问题,但如果你在使用django-registration,它可以很容易地总结出来。

在你的登录和注销链接(让我们说在你的页面标题)添加下一个参数的链接将登录或注销。您的链接应该是这样的。

<li><a href="http://www.noobmovies.com/accounts/login/?next={{ request.path | urlencode }}">Log In</a></li>

<li><a href="http://www.noobmovies.com/accounts/logout/?next={{ request.path | urlencode }}">Log Out</a></li>

这很简单,没有其他需要做的,登出时,他们将立即重定向到他们所在的页面,为了登录,他们将填写表格,然后将重定向到他们所在的页面。即使他们错误地尝试登录,它仍然可以工作。