[Django]-Redirect to a url with query string in Django

50πŸ‘

βœ…

Using reverse and passing the name of url we can redirect to url with query string:

#urls.py

url(r'^search/$', views.search, name='search_view')

#views.py

from django.shortcuts import redirect, reverse

# in method
return redirect(reverse('search_view') + '?item=4')
πŸ‘€Saad Abdullah

16πŸ‘

I know this question is a bit old, but someone will stumble upon this while searching redirect with query string, so here is my solution:

import urllib
from django.shortcuts import redirect

def redirect_params(url, params=None):
    response = redirect(url)
    if params:
        query_string = urllib.urlencode(params)
        response['Location'] += '?' + query_string
    return response

def your_view(request):
    your_params = {
        'item': 4
    }
    return redirect_params('search_view', your_params)
πŸ‘€fixmycode

6πŸ‘

If you already have a request (with a GET containing some parameters), and you want to redirect to a different view with the same args, kwargs and parameters, we can use the QueryDict object to url encode itself:

def view(request, *args, **kwargs):
    return redirect(
        reverse('your:view:path', args=args, kwargs=kwargs) + 
        '?' + request.GET.urlencode()
    )

2πŸ‘

A more generic option;

from urllib.parse import urlencode
from django.shortcuts import redirect as django_redirect


def redirect(url, *args, params=None, **kwargs):
    query_params = ""
    if params:
        query_params += '?' + urlencode(params)
    return django_redirect(url+query_params, *args, **kwargs)

πŸ‘€karuhanga

0πŸ‘

To redirect to another page while carrying along the the current query strings:

views.py:

from django.urls import reverse
from django.shortcuts import redirect

def my_view(request):
    #get the current query string
    q = request.META['QUERY_STRING']
    return redirect(reverse('search_view') + '?' + q)
πŸ‘€adigunsherif

Leave a comment