Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to a url with query string in Django

Tags:

How can I go to a specific URL with parameters like if I have view

def search(request): 

and in urls.py

^search/$  

and what I need to do is to redirect like search/?item=4

c = {} render_to_response("search.html",c)  

works fine, but

render_to_response("search.html/?item=" + itemID, c ) 

it says no template found ( I know there is no template like search.html/?item= ) but how can I pass parameters or use query string to redirect?

like image 447
Saad Abdullah Avatar asked Nov 05 '13 08:11

Saad Abdullah


People also ask

How do I redirect a request in Django?

Django Redirects: A Super Simple Example Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .

What is the difference between HttpResponseRedirect and redirect?

There is a difference between the two: In the case of HttpResponseRedirect the first argument can only be a url . redirect which will ultimately return a HttpResponseRedirect can accept a model , view , or url as it's "to" argument. So it is a little more flexible in what it can "redirect" to.

Can we pass a dictionary in redirect Django?

We can redirect to models and pass a dictionary of arguments to the redirect function. This is useful if we want to pass a query string to the redirect URL. You can also create a permanent redirect by passing the permanent=True argument to the redirect function.


2 Answers

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') 
like image 84
Saad Abdullah Avatar answered Sep 21 '22 12:09

Saad Abdullah


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) 
like image 34
fixmycode Avatar answered Sep 22 '22 12:09

fixmycode