How can I redirect to a different URL in Django?

天涯浪子 提交于 2021-02-16 18:51:46

问题


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.


回答1:


You can use HttpResponseRedirect:

from django.http import HttpResponseRedirect

# ...

return HttpResponseRedirect('/url/url1/')

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




回答2:


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

from django.http import HttpResponseRedirect
return HttpResponseRedirect('/url-name-here/')



回答3:


you can try this :

from django.shortcuts import redirect
return redirect(f'/customer/{pk}')


来源:https://stackoverflow.com/questions/20873691/how-can-i-redirect-to-a-different-url-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!