Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I redirect to a different URL in Django?

I have two pages, one which is to display details for a specific item and another to search for items. Let's say that the urls.py is properly configured for both of them and within views.py for my app, I have:

def item(request, id):
    return render(request, 'item.html', data)

def search(request):
    #use GET to get query parameters
    if len(query)==1:
        #here, I want to redirect my request to item, passing in the id
    return render(request, 'search.html', data)

What do I do to properly redirect the request? I've tried return item(request, id) and that renders the correct page, but it doesn't change the URL in the address bar. How can I make it actually redirect instead of just rendering my other page? The URL pattern for the item page is /item/{id}. I've looked at the answer to similar questions on SO and the documentation, but still couldn't figure it out.

Edit: I just started learning Python less than a week ago and the other answer isn't clear enough to help me out.

Edit 2: Nvm, not sure what I did wrong before, but it worked when I tried it again.

like image 493
Lunyx Avatar asked Jan 01 '14 21:01

Lunyx


People also ask

How do I redirect a URL to another URL?

Add a new URL redirectClick the URL Redirects tab. In the upper right, click Add URL redirect. In the right panel, select the Standard or Flexible redirect type. A standard redirect is used to redirect one URL to another.

How do I redirect from one URL to another in Python?

The redirect() function allows us to redirect a user to the URL of our choice. In the Flask application that we are building so far, we have a /shortenurl route that checks to see what method type is in use. If it is a GET request, we are simply returning some text to the user.

Can you redirect any URL?

Again, you can permanently redirect an old domain to a new one by using a 301 redirect type. This carries over Google PageRank and other SEO factors like page authority. Changing a post's URL. You can avoid the 404 error by redirecting any deleted page URLs to a new one.


2 Answers

You can use HttpResponseRedirect:

from django.http import HttpResponseRedirect

# ...

return HttpResponseRedirect('/url/url1/')

Where "url" and "url1" equals the path to the redirect.

like image 69
Joe Avatar answered Oct 19 '22 08:10

Joe


Just minute suggestion from the above answer for the change in import statement

from django.http import HttpResponseRedirect
return HttpResponseRedirect('/url-name-here/')
like image 34
MbeforeL Avatar answered Oct 19 '22 07:10

MbeforeL