AoA, How can I goto a specific URL with parameters like if I have view
def search(request):
and in urls.py
^search/$
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)
the answer is pretty simple. Using reverse and passing name of url can redirect to url with query string
url(r'^search/$', views.search, name='search_view')
from django.shortcuts import redirect, reverse
# in method
return redirect(reverse('search_view') + '?item=4')
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)
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)