如何在Django中重定向到其他URL? [英] How can I redirect to a different URL in Django?
问题描述
我有两页,一页显示特定项目的详细信息,另一页搜索项目.假设urls.py已为它们都正确配置,并且在我的应用程序的views.py中,我具有:
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)
我该怎么做才能正确地重定向请求?我尝试了返回项目(请求,id)
,它可以呈现正确的页面,但是它不会更改地址栏中的URL.我如何才能使其真正重定向,而不仅仅是呈现其他页面?项目页面的URL模式为/item/{id}
.我已经看过SO和文档中类似问题的答案,但仍无法弄清楚.
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.
我不到一个星期前才开始学习Python,另一个答案还不够明确,无法帮助我.
I just started learning Python less than a week ago and the other answer isn't clear enough to help me out.
Nvm,不确定我以前做错了什么,但是当我再次尝试时它起作用了.
Edit 2: Nvm, not sure what I did wrong before, but it worked when I tried it again.
推荐答案
You can use HttpResponseRedirect
:
from django.http import HttpResponseRedirect
# ...
return HttpResponseRedirect('/url/url1/')
其中"url"和"url1"等于重定向的路径.
Where "url" and "url1" equals the path to the redirect.
这篇关于如何在Django中重定向到其他URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!