How to make a redirect and keep the query string?
Asked Answered
I

4

20

I want to make a redirect and keep what is the query string. Something like self.redirect plus the query parameters that was sent. Is that possible?

Infarct answered 13/5, 2012 at 6:26 Comment(5)
Where do you want to keep it? In a session?Vinson
Can't I just pass on the query parameters via HTTP GET?Infarct
Of course, I don't know which framework you are using, but that should be straightforward. In straight http you would send a 301 or 303 with the Location header set to the redirect url plus the query params you want to keep.Vinson
Yes, that's what I want to do and I think it is straightforward. I use webapp2 and google app engine, I'm adding those tags to the question.Infarct
@Wooble I could try the parameters one by one but I'm looking for a way to add the entire query string in a oneliner. I know the names of the parameters I want to get via HTTP GET and I want to pass on their values. I figure there should be a way to pass on the entire map instead of one variable at a time.Infarct
H
22
newurl = '/my/new/route?' + urllib.urlencode(self.request.params)
self.redirect(newurl)
Happen answered 14/5, 2012 at 19:57 Comment(2)
can not run in tornado 4Giacinta
Can use urllib.parse.urlencode(self.request.query_arguments, doseq=True) in then new version.Counterblow
L
11

You can fetch the query string to the current request with self.request.query_string; thus you can redirect to a new URL with self.redirect('/new/url?' + self.request.query_string).

Loidaloin answered 15/5, 2012 at 4:3 Comment(1)
can not run in tornado 4Giacinta
R
5

Use the RedirectView.

from django.views.generic.base import RedirectView
path('go-to-django/', RedirectView.as_view(url='https://djangoproject.com', query_string=True), name='go-to-django')
Rosin answered 8/10, 2020 at 21:38 Comment(0)
H
2

This worked for me in Django 2.2. The query string is available as a QueryDict instance request.GET for an HTTP GET and request.POST for an HTTP POST. Convert these to normal dictionaries and then use urlencode.

from django.utils.http import urlencode

query_string = urlencode(request.GET.dict())  # or request.GET.urlencode()

new_url = '/my/new/route' + '?' + query_string

See https://docs.djangoproject.com/en/2.2/ref/request-response/.

Highroad answered 1/10, 2019 at 20:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.