[英]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:假设 urls.py 已为它们和我的应用程序的 views.py 正确配置,我有:
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.我试过return item(request, id)
并呈现正确的页面,但它不会更改地址栏中的 URL。 How can I make it actually redirect instead of just rendering my other page?我怎样才能让它真正重定向而不是仅仅呈现我的其他页面? The URL pattern for the item page is /item/{id}
.项目页面的 URL 模式是/item/{id}
。 I've looked at the answer to similar questions on SO and the documentation, but still couldn't figure it out.我已经查看了关于 SO 和文档的类似问题的答案,但仍然无法弄清楚。
Edit: I just started learning Python less than a week ago and the other answer isn't clear enough to help me out.编辑:我不到一周前才开始学习 Python,另一个答案不够清楚,无法帮助我。
Edit 2: Nvm, not sure what I did wrong before, but it worked when I tried it again.编辑 2:Nvm,不确定我之前做错了什么,但是当我再次尝试时它起作用了。
You can use HttpResponseRedirect
:您可以使用HttpResponseRedirect
:
from django.http import HttpResponseRedirect
# ...
return HttpResponseRedirect('/url/url1/')
Where "url" and "url1" equals the path to the redirect.其中“url”和“url1”等于重定向的路径。
Just minute suggestion from the above answer for the change in import statement从上面的答案中对导入语句的更改提出了一点建议
from django.http import HttpResponseRedirect
return HttpResponseRedirect('/url-name-here/')
you can try this :你可以试试这个:
from django.shortcuts import redirect
return redirect(f'/customer/{pk}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.