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

假设我当前的URL是:

.../user/profile/

如何将此返回到模板?


当前回答

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

{{请求。路径}}和{{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中包含请求,它已经在那里了。

在Django 3中,你需要使用url template标签:

{% url 'name-of-your-user-profile-url' possible_context_variable_parameter %}

具体示例请参见文档

下面的代码帮助我:

 {{ request.build_absolute_uri }}