Is there a way to get the current page URL and all its parameters in a Django template?
For example, a templatetag that would print a full URL like /foo/bar?param=1&baz=2
We can access the query params from the request in Django from the GET attribute of the request. To get the first or only value in a parameter simply use the get() method. To get the list of all values in a parameter use getlist() method.
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).
You can do that by using request. META['HTTP_REFERER'] , but it will exist if only your tab previous page was from your website, else there will be no HTTP_REFERER in META dict . So be careful and make sure that you are using . get() notation instead.
Write a custom context processor. e.g.
def get_current_path(request): return { 'current_path': request.get_full_path() }
add a path to that function in your TEMPLATE_CONTEXT_PROCESSORS
settings variable, and use it in your template like so:
{{ current_path }}
If you want to have the full request
object in every request, you can use the built-in django.core.context_processors.request
context processor, and then use {{ request.get_full_path }}
in your template.
See:
Use Django's build in context processor to get the request in template context. In settings add request
processor to TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS = ( # Put your context processors here 'django.core.context_processors.request', )
And in template use:
{{ request.get_full_path }}
This way you do not need to write any new code by yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With