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

假设我当前的URL是:

.../user/profile/

如何将此返回到模板?


当前回答

3 . Django > 我不改变设置或任何东西。 我在模板文件中添加了下面的代码。

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

在view.py中将请求变量传递给模板文件。

view.py:

def view_node_taxon(request, cid):
    showone = get_object_or_404(models.taxon, id = cid)
    context = {'showone':showone,'request':request}
    mytemplate  = loader.get_template('taxon/node.html')
    html = mytemplate.render(context)
    return HttpResponse(html)

其他回答

{{请求。路径}}和{{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模板中 简单地从{{request.path}}获取当前url 获取参数为{{request.get_full_path}}的完整url

注意: 你必须在django TEMPLATE_CONTEXT_PROCESSORS中添加request

3 . Django > 我不改变设置或任何东西。 我在模板文件中添加了下面的代码。

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

在view.py中将请求变量传递给模板文件。

view.py:

def view_node_taxon(request, cid):
    showone = get_object_or_404(models.taxon, id = cid)
    context = {'showone':showone,'request':request}
    mytemplate  = loader.get_template('taxon/node.html')
    html = mytemplate.render(context)
    return HttpResponse(html)

如果你正在使用渲染部分,最好使用

{{请求。path_info}}

它返回页面的确切url

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

from django.shortcuts import render

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

##template
{{ app_url }}