小编典典

如何在Django模板中获取当前URL?

django

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

说我目前的网址是:

.../user/profile/

如何将其返回到模板?


阅读 814

收藏
2020-03-26

共2个答案

小编典典

Django 1.9及更高版本:

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

旧:

## 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 }}
2020-03-26
小编典典

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

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

或通过

{{ request.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',
)

然后,假设你发送了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)
    )
2020-03-26