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
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?
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.
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.
Just use the same label {% url 'index' %} . You may use each name in urls.py to link to the url. Save this answer.
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.
You'll need a custom tag. There are a couple on djangosnippets - this one looks pretty comprehensive.
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