Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get URL of current page, including parameters, in a template?

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

like image 260
Matt Hampel Avatar asked Jul 14 '10 17:07

Matt Hampel


People also ask

How do I get all query parameters in Django?

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.

How does Django treat a request url string?

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).

How can I get previous url in Django?

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.


2 Answers

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:

  • Custom Context Processors
  • HTTPRequest's get_full_path() method.
like image 178
Sam Dolan Avatar answered Oct 11 '22 17:10

Sam Dolan


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.

like image 44
Mariusz Jamro Avatar answered Oct 11 '22 15:10

Mariusz Jamro