Reputation: 388
My website has a list of pages that are under /record and available only with query parameters of type and id. Like so:
/record?type=poem&id=175
I am using the django next redirect to go from the login page to the previous page. I initially used href="{% url 'auth:login' %}?next={{ request.path }}"
to redirect, but it didn't take the query parameters (i.e type and id). This takes the user to
/login/?next=/record
I then used href="'{% url 'auth:login' %}?next={{ request.path }}'+window.location.search"
. However, this doesn't work as well. This takes the user to
/login/?next=/record?type=poem&id=175
but it finally redirects to
/record
How do I redirect using next along with query parameters? Is this behavior not possible?
Upvotes: 2
Views: 4743
Reputation: 175
You need to escape special characters in the URL, namely '?', '&' and '='.
While there is django.utils.encoding.escape_uri_path, it doesn't escape the ampersand (&), which is a problem because it will be interpreted as the end of the next
parameter and the beginning of another.
Instead, you can use urllib.parse.quote:
from urllib.parse import quote
current_url_escaped = quote(request.get_full_path())
and in the template:
href="{% url 'auth:login' %}?next={{ current_url_escaped }}
Upvotes: 4
Reputation: 47876
You can use HttpRequest.get_full_path()
method along with urlencode
template filter to get the current url along with the query string.
HttpRequest.get_full_path()
Returns the path, plus an appended query string, if applicable.
href="{% url 'auth:login' %}?next={{request.get_full_path|urlencode}}
Upvotes: 3