19

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?

Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
  • 1
    Where do you want to keep it? In a session? – XORcist May 13 '12 at 09:27
  • Can't I just pass on the query parameters via HTTP GET? – Niklas Rosencrantz May 14 '12 at 08:16
  • 1
    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. – XORcist May 14 '12 at 10:32
  • 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. – Niklas Rosencrantz May 14 '12 at 12:23
  • @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. – Niklas Rosencrantz May 15 '12 at 05:52

4 Answers4

21
newurl = '/my/new/route?' + urllib.urlencode(self.request.params)
self.redirect(newurl)
Steven Almeroth
  • 7,758
  • 2
  • 50
  • 57
10

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

Nick Johnson
  • 100,655
  • 16
  • 128
  • 198
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')
karuhanga
  • 3,010
  • 1
  • 27
  • 30
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/.

GCru
  • 426
  • 6
  • 8