391

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?

daaawx
  • 3,273
  • 2
  • 17
  • 16
dotty
  • 40,405
  • 66
  • 150
  • 195
  • 3
    possible duplicate of [Reading path in templates](http://stackoverflow.com/questions/2127937/reading-path-in-templates) – Mark Mikofski Jun 19 '14 at 08:53
  • 2
    All the below answers made me think I needed to do some gymnastics to get access to `request` in a template. In Django 1.10 I just access `{{request.path}}` in the template and it works. By default `django.core.context_processors.request` is already configured in settings.py if you used `startproject` – User Feb 21 '17 at 11:48

16 Answers16

356

Django 1.9 and above:

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

Old:

## 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 }}
Aleksei Khatkevich
  • 1,923
  • 2
  • 10
  • 27
httpete
  • 5,875
  • 4
  • 32
  • 41
  • 2
    A bit laconic, and not correct. It's `render_to_response`, and not `render_to_request`. And you can't define `TEMPLATE_CONTEXT_PROCESSORS` as you do in settings.py, without mentioning the other default processors that may well be used in the templates! – RedGlyph Apr 15 '12 at 14:05
  • 11
    As of 2016, you no longer need to add anything to views.py. As long as django.core.context_processors.request is loaded in TEMPLATE_CONTEXT_PROCESSORS - you have access to {{ request.path }} from the template. – Routhinator Apr 24 '16 at 20:14
  • 11
    `request.path` does not include query parameters like `?foo=bar`. Use `request.get_full_path` instead. – Flimm Dec 07 '16 at 13:32
  • @Routhinator agree with you. but it's nice to know that those middleware needs to be included to make this happen. – Marshall X Aug 26 '17 at 21:18
  • 1
    As commented in other answers by @Quentin and @user you should include `urlencode` if you plan to use it in a link, typically: `.../accounts/login?next={{ request.get_full_path | urlencode }}...` – Tadeo Jun 24 '20 at 15:05
303

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)
    )
RedGlyph
  • 11,309
  • 6
  • 37
  • 49
  • 4
    I used an extended generic class view, and it was unnecessary to add `request` to the context. – Bobort Jun 04 '12 at 16:32
  • Definitely cleaner to avoid hard coding the TCP list, but docs.djangoproject.com/en/dev/topics/settings/#default-settings says : `Note that a settings file should not import from global_settings, because that’s redundant` – user Apr 06 '14 at 19:47
  • 3
    `return render(request, 'user/profile.html', {'title': 'User profile'})` is shorter – Richard de Wit Jun 26 '14 at 10:43
  • 3
    remember to include urlencode i.e. `{{request.get_full_path|urlenode}}` if you are redirecting – user Jul 02 '14 at 14:46
  • how to get parameters from get_full_path ?? – numerah Dec 29 '14 at 10:48
  • @user Why do we need to use `urlenode`? If I use it like this: `request.build_absolute_uri|urlencode`, I get this: `http://127.0.0.1:8000/2020/8/8/http%3A//127.0.0.1%3A8000/2020/8/8/just-a-test-post` and without it I get normal `http://127.0.0.1:8000/2020/8/8/just-a-test-post` – ruslaniv Aug 08 '20 at 15:05
  • Indeed, I see no need to use `urlencode` (it is `urlencode`, not `urlenode`) since this is already an URL. It would escape characters that mustn't be. – RedGlyph Aug 16 '20 at 10:59
41

The below code helps me:

 {{ request.build_absolute_uri }}
Angel F Syrus
  • 1,984
  • 8
  • 23
  • 43
17

Both {{ request.path }} and {{ request.get_full_path }} return the current URL but not absolute URL, for example:

your_website.com/wallpapers/new_wallpaper

Both will return /new_wallpaper/ (notice the leading and trailing slashes)

So you'll have to do something like

{% if request.path == '/new_wallpaper/' %}
    <button>show this button only if url is new_wallpaper</button>
{% endif %}

However, you can get the absolute URL using (thanks to the answer above)

{{ request.build_absolute_uri }}

NOTE: you don't have to include requests in settings.py, it's already there.

Mujeeb Ishaque
  • 2,259
  • 24
  • 16
6

In django template
Simply get current url from {{request.path}}
For getting full url with parameters {{request.get_full_path}}

Note: You must add request in django TEMPLATE_CONTEXT_PROCESSORS

Savad KP
  • 1,625
  • 3
  • 28
  • 40
6

I suppose send to template full request is little bit redundant. I do it this way

from django.shortcuts import render

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

##template
{{ app_url }}
Kalob Taulien
  • 1,817
  • 17
  • 22
Radren
  • 307
  • 4
  • 6
4

The other answers were incorrect, at least in my case. request.path does not provide the full url, only the relative url, e.g. /paper/53. I did not find any proper solution, so I ended up hardcoding the constant part of the url in the View before concatenating it with request.path.

CoderGuy123
  • 6,219
  • 5
  • 59
  • 89
3

You can get the url without parameters by using {{request.path}} You can get the url with parameters by using {{request.get_full_path}}

Raj Kalathiya
  • 385
  • 2
  • 8
3

if you are using render partial it's better to use

{{ request.path_info }}

It returns the exact url of the page

2

For Django > 3 I do not change settings or anything. I add the below code in the template file.

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

and in view.py pass request variable to the template file.

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)
Darwin
  • 1,695
  • 1
  • 19
  • 29
1

This is an old question but it can be summed up as easily as this if you're using django-registration.

In your Log In and Log Out link (lets say in your page header) add the next parameter to the link which will go to login or logout. Your link should look like this.

<li><a href="http://www.noobmovies.com/accounts/login/?next={{ request.path | urlencode }}">Log In</a></li>

<li><a href="http://www.noobmovies.com/accounts/logout/?next={{ request.path | urlencode }}">Log Out</a></li>

That's simply it, nothing else needs to be done, upon logout they will immediately be redirected to the page they are at, for log in, they will fill out the form and it will then redirect to the page that they were on. Even if they incorrectly try to log in it still works.

Flimm
  • 136,138
  • 45
  • 251
  • 267
Chris Hawkes
  • 11,923
  • 6
  • 58
  • 68
1

Above answers are correct and they give great and short answer.

I was also looking for getting the current page's url in Django template as my intention was to activate HOME page, MEMBERS page, CONTACT page, ALL POSTS page when they are requested.

I am pasting the part of the HTML code snippet that you can see below to understand the use of request.path. You can see it in my live website at http://pmtboyshostelraipur.pythonanywhere.com/

<div id="navbar" class="navbar-collapse collapse">
  <ul class="nav navbar-nav">
        <!--HOME-->
        {% if "/" == request.path %}
      <li class="active text-center">
          <a href="/" data-toggle="tooltip" title="Home" data-placement="bottom">
            <i class="fa fa-home" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true">
            </i>
          </a>
      </li>
      {% else %}
      <li class="text-center">
          <a href="/" data-toggle="tooltip" title="Home" data-placement="bottom">
            <i class="fa fa-home" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true">
            </i>
          </a>
      </li>
      {% endif %}

      <!--MEMBERS-->
      {% if "/members/" == request.path %}
      <li class="active text-center">
        <a href="/members/" data-toggle="tooltip" title="Members"  data-placement="bottom">
          <i class="fa fa-users" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
        </a>
      </li>
      {% else %}
      <li class="text-center">
        <a href="/members/" data-toggle="tooltip" title="Members"  data-placement="bottom">
          <i class="fa fa-users" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
        </a>
      </li>
      {% endif %}

      <!--CONTACT-->
      {% if "/contact/" == request.path %}
      <li class="active text-center">
        <a class="nav-link" href="/contact/"  data-toggle="tooltip" title="Contact"  data-placement="bottom">
            <i class="fa fa-volume-control-phone" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
          </a>
      </li>
      {% else %}
      <li class="text-center">
        <a class="nav-link" href="/contact/"  data-toggle="tooltip" title="Contact"  data-placement="bottom">
            <i class="fa fa-volume-control-phone" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
          </a>
      </li>
      {% endif %}

      <!--ALL POSTS-->
      {% if "/posts/" == request.path %}
      <li class="text-center">
        <a class="nav-link" href="/posts/"  data-toggle="tooltip" title="All posts"  data-placement="bottom">
            <i class="fa fa-folder-open" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
          </a>
      </li>
      {% else %}
      <li class="text-center">
        <a class="nav-link" href="/posts/"  data-toggle="tooltip" title="All posts"  data-placement="bottom">
            <i class="fa fa-folder-open" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
          </a>
      </li>
      {% endif %}
</ul>

hygull
  • 8,464
  • 2
  • 43
  • 52
  • 2
    A small suggestion -- if all you are doing is checking whether to add the `active` class to each `li` element, why not just do that inline within one `li` element: `
  • ....
  • ` instead of a giant if/else block for the whole `li`? That would save a whole bunch of redundant code :) – tatlar Sep 05 '18 at 06:33