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?
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/ .
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.
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.
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')
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With