I was wondering how to get the current URL within a template.
Say my current URL is:
.../user/profile/
How do I return this to the template?
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 TCP
TEMPLATE_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_response
from django.template import RequestContext
def index(request):
return render_to_response(
'user/profile.html',
{ 'title': 'User profile' },
context_instance=RequestContext(request)
)