How to get the current URL within a Django template? How to get the current URL within a Django template? django django

How to get the current URL within a Django template?


Django 1.9 and above:

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

Old:

## settings.pyTEMPLATE_CONTEXT_PROCESSORS = (    'django.core.context_processors.request',)## views.pyfrom django.template import *def home(request):    return render_to_response('home.html', {}, context_instance=RequestContext(request))## template{{ request.path }}


You can fetch the URL in your template like this:

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

or by

{{ request.path }} if you don't need the extra parameters.

Some precisions and corrections should be brought to hypete's and Igancio's answers, I'll just summarize the whole idea here, for future reference.

If you need the request variable in the template, you must add the 'django.core.context_processors.request' to the TEMPLATE_CONTEXT_PROCESSORS settings, it's not by default (Django 1.4).

You must also not forget the other context processors used by your applications. So, to add the request to the other default processors, you could add this in your settings, to avoid hard-coding the default processor list (that may very well change in later versions):

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCPTEMPLATE_CONTEXT_PROCESSORS = TCP + (    'django.core.context_processors.request',)

Then, provided you send the request contents in your response, for example as this:

from django.shortcuts import render_to_responsefrom django.template import RequestContextdef index(request):    return render_to_response(        'user/profile.html',        { 'title': 'User profile' },        context_instance=RequestContext(request)    )


The below code helps me:

 {{ request.build_absolute_uri }}