Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26652

How to make a redirect and keep the query string?

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?

Upvotes: 21

Views: 15241

Answers (4)

karuhanga
karuhanga

Reputation: 3322

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

Upvotes: 5

GCru
GCru

Reputation: 516

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

Upvotes: 2

Nick Johnson
Nick Johnson

Reputation: 101139

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

Upvotes: 11

Steven Almeroth
Steven Almeroth

Reputation: 8192

newurl = '/my/new/route?' + urllib.urlencode(self.request.params)
self.redirect(newurl)

Upvotes: 22

Related Questions