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

假设我当前的URL是:

.../user/profile/

如何将此返回到模板?


当前回答

其他答案都是错的,至少对我来说是这样。请求。Path不提供完整的url,只提供相对的url,例如/paper/53。我没有找到任何合适的解决方案,所以我最终在视图中硬编码url的常量部分,然后将其与request.path连接。

其他回答

这是一个老问题,但如果你在使用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>

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

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

Django 1.9及以上版本:

## template
{{ request.path }}  #  -without GET parameters 
{{ request.get_full_path }}  # - with GET parameters

Old:

## settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)

## views.py
from django.template import *

def home(request):
    return render_to_response('home.html', {}, context_instance=RequestContext(request))

## template
{{ request.path }}

使用的例子:

 <!-- BRAND -->
        <div class="brand">
            <div class="logo">
                {% if request.get_full_path == '/' %}
                    <a href="{% url 'front:homepage' %}" class="first-logo big-logo">
                        <img src="{% static 'assets/images/logo-big.svg' %}"
                             alt="pozitiv">
                    </a>

                    <a href="{% url 'front:homepage' %}" class="second-logo mobile-logo">
                        <img src="{% static 'assets/images/logo.svg' %}"
                             alt="<?php echo WEBSITE_NAME; ?>" >
                    </a>

                {% else %}

                    <a href="{% url 'front:homepage' %}">
                        <img src="{% static 'assets/images/logo.svg' %}"
                             alt="<?php echo WEBSITE_NAME; ?>" style="width: 320px; margin: -20px 0 0 0;">
                    </a>
                {% endif %}
            </div>
        </div>

要将get参数传递给模板, 你可以通过views.py文件传递它

例子:

return render(request, 'test.html',{'get_parameter_name' : get_parameter_value})

并在模板中使用如下:

{{get_parameter_name}}