我想知道如何在模板中获得当前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)

其他回答

你可以像这样在模板中获取URL:

<p>URL of this page: {{ request.get_full_path }}</p>

或通过

{{请求。如果不需要额外的参数,则使用Path}}。

hypete和Igancio的回答应该有一些精确和更正,我只是在这里总结一下整个想法,以供将来参考。

如果你需要在模板中使用request变量,你必须添加django.core.context_processors。request'到TEMPLATE_CONTEXT_PROCESSORS设置,它不是默认的(Django 1.4)。

您还不能忘记应用程序使用的其他上下文处理器。所以,要将请求添加到其他默认处理器,你可以在你的设置中添加这个,以避免硬编码默认处理器列表(这在以后的版本中很可能会改变):

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

TEMPLATE_CONTEXT_PROCESSORS = TCP + (
    'django.core.context_processors.request',
)

然后,如果你在响应中发送请求内容,例如:

from django.shortcuts import render_to_response
from django.template import RequestContext

def index(request):
    return render_to_response(
        'user/profile.html',
        { 'title': 'User profile' },
        context_instance=RequestContext(request)
    )

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

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

{{请求。path_info}}

它返回页面的确切url

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

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

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

对于你的模板

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

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)