Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a url with the same GET parameters as the current page in a Django template

Tags:

python

django

I have a certain link to a url in a Django template. I would like to grab all the GET parameters of the current page url and add them to the url of the template's link. The current page might have zero GET parameters.

like image 885
snakile Avatar asked Oct 12 '12 17:10

snakile


People also ask

How do I pass URL parameters in Django?

Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.

How can I get current URL in Django?

Run the following command to start the Django server. Execute the following URL from the browser to display the domain name of the current URL. The geturl1() function will be called for this URL that will send the domain name to the index. html file.

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


1 Answers

Include the django.core.context_processors.request context processor in your settings.py, then use the request object in your template's links:

<a href="{% url 'my_url' %}?{{ request.META.QUERY_STRING }}">

This will cause links from a page without any GET variables to have a trailing ? but that's harmless. If that's not acceptable, you could test for them first:

<a href="{% url 'my_url' %}{% if request.META.QUERY_STRING %}?{{ request.META.QUERY_STRING }}{% endif %}">
like image 196
dgel Avatar answered Oct 20 '22 05:10

dgel