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
- [Django]-How to get the domain name of my site within a Django template?
- [Django]-Permission Denied error with Django while uploading a file
- [Django]-Request.data in DRF vs request.body in Django
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()
)
- [Django]-Timestamp fields in django
- [Django]-Pipfile.lock out of date
- [Django]-Django Aggregation: Sum return value only?
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
- [Django]-Remove Labels in a Django Crispy Forms
- [Django]-Django 1.8 β what's the difference between migrate and makemigrations?
- [Django]-How to access Enum types in Django templates
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
- [Django]-Django 1.7 β makemigrations not detecting changes
- [Django]-How to render Django form errors not in a UL?
- [Django]-Django Admin β Disable the 'Add' action for a specific model
Source:stackexchange.com