364
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 }}
304
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)
)
- [Django]-What is the difference between cached_property in Django vs. Python's functools?
- [Django]-Rendering a value as text instead of field inside a Django Form
- [Django]-Django Cannot set values on a ManyToManyField which specifies an intermediary model. Use Manager instead
- [Django]-Do django db_index migrations run concurrently?
- [Django]-Django – {% csrf_token %} was used in a template, but the context did not provide the value
- [Django]-Getting Values of QuerySet in Django
18
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.
- [Django]-How to resize the new uploaded images using PIL before saving?
- [Django]-How to revert the last migration?
- [Django]-ImportError: Failed to import test module:
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
- [Django]-Django – "Incorrect type. Expected pk value, received str" error
- [Django]-Django: how to do calculation inside the template html page?
- [Django]-Django model blank=False does not work?
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 }}
- [Django]-Django REST framework post array of objects
- [Django]-Django Form File Field disappears on form error
- [Django]-Django-rest-framework returning 403 response on POST, PUT, DELETE despite AllowAny permissions
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
.
- [Django]-Where is a good place to work on accounts/profile in Django with the Django registration app?
- [Django]-Django: Safely Remove Old Migrations?
- [Django]-Django: Reference to an outer query may only be used in a subquery
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}}
- [Django]-Django: Error: You don't have permission to access that port
- [Django]-How to use refresh token to obtain new access token on django-oauth-toolkit?
- [Django]-Get count of related model efficiently in Django
3
if you are using render partial it’s better to use
{{ request.path_info }}
It returns the exact url of the page
- [Django]-Django QuerySet order
- [Django]-What is a django.utils.functional.__proxy__ object and what it helps with?
- [Django]-Celery. Decrease number of processes
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)
- [Django]-Visual Editor for Django Templates?
- [Django]-Factory-boy create a list of SubFactory for a Factory
- [Django]-Cannot set Django to work with smtp.gmail.com
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.
- [Django]-Annotate a queryset with the average date difference? (django)
- [Django]-Django – Rotating File Handler stuck when file is equal to maxBytes
- [Django]-How to server HTTP/2 Protocol with django
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>
- [Django]-Data Mining in a Django/Postgres application
- [Django]-AccessDenied when calling the CreateMultipartUpload operation in Django using django-storages and boto3
- [Django]-Django REST Framework: how to substitute null with empty string?
0
In Django 3, you want to use url template tag:
{% url 'name-of-your-user-profile-url' possible_context_variable_parameter %}
For an example, see the documentation
- [Django]-Duplicate column name
- [Django]-Python Asyncio in Django View
- [Django]-How to add new languages into Django? My language "Uyghur" or "Uighur" is not supported in Django
0
Use example:
<!-- BRAND -->
<div class="brand">
<div class="logo">
{% if request.get_full_path == '/' %}
<a href="{% url 'front:homepage' %}" class="first-logo big-logo">
<img src="{% static 'assets/images/logo-big.svg' %}"
alt="pozitiv">
</a>
<a href="{% url 'front:homepage' %}" class="second-logo mobile-logo">
<img src="{% static 'assets/images/logo.svg' %}"
alt="<?php echo WEBSITE_NAME; ?>" >
</a>
{% else %}
<a href="{% url 'front:homepage' %}">
<img src="{% static 'assets/images/logo.svg' %}"
alt="<?php echo WEBSITE_NAME; ?>" style="width: 320px; margin: -20px 0 0 0;">
</a>
{% endif %}
</div>
</div>
- [Django]-Django-celery: No result backend configured
- [Django]-CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true
- [Django]-Sending an SMS to a Cellphone using Django
0
To pass the get parameter to template,
you can pass it via views.py
file
Example:
return render(request, 'test.html',{'get_parameter_name' : get_parameter_value})
And use in template like:
{{get_parameter_name}}
- [Django]-How to delete project in django
- [Django]-Pytest.mark.parametrize with django.test.SimpleTestCase
- [Django]-NumPy array is not JSON serializable
0
If you are using js in the template as well, you can do this:
In you js
document.addEventListener('DOMContentLoaded', function() {
...
getUrl();
}
function getUrl() {
let someDiv = document.querySelector(`#someDiv`);
someDiv.innerHTML = window.location.href;
}
for your template
...
<div id="someDiv"><div>
...
- [Django]-How to make two django projects share the same database
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
- [Django]-How does one make logging color in Django/Google App Engine?