Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link to Current Page in Django, with Additional GET Params?

Tags:

url

django

How do I place an HTML link what refers to the current page, and which adds additional GET parameters (or overwriting existing ones, if they already exist)?

Right now I have something like:

 <a href="{{ request.path }}?Key=Value"> My Link </a>

Currently, request is passed to the page. If request.path is https://stackoverflow.com/, then the resulting link becomes https://stackoverflow.com/?Key=Value

The problem?

But of course, if the current URL is https://stackoverflow.com/?PrevKey=PrevValue then it becomes:

https://stackoverflow.com/?PrevKey=PrevValue?Key=Value

Notice the incorrect second question mark -- it should in fact be:

https://stackoverflow.com/?PrevKey=PrevValue&Key=Value

Furthermore, if there is already a key with the same name, then instead of overwriting it, my current solution ignores it -- which is wrong.

How do I solve these two problems?

like image 996
user541686 Avatar asked Jun 20 '11 17:06

user541686


People also ask

How do I pass parameters via URL 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 do I pass multiple parameters in URL?

To add a parameter to the URL, add a /#/? to the end, followed by the parameter name, an equal sign (=), and the value of the parameter. You can add multiple parameters by including an ampersand (&) between each one.

How do I link to another page in Django?

Just use the same label {% url 'index' %} . You may use each name in urls.py to link to the url. Save this answer.

How do I get 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.


1 Answers

You'll need a custom tag. There are a couple on djangosnippets - this one looks pretty comprehensive.

like image 74
Daniel Roseman Avatar answered Nov 24 '22 09:11

Daniel Roseman