[英]How can I redirect to a different URL in Django?
我有兩頁,一頁是顯示特定項目的詳細信息,另一頁是搜索項目。 假設 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)
我該怎么做才能正確重定向請求? 我試過return item(request, id)
並呈現正確的頁面,但它不會更改地址欄中的 URL。 我怎樣才能讓它真正重定向而不是僅僅呈現我的其他頁面? 項目頁面的 URL 模式是/item/{id}
。 我已經查看了關於 SO 和文檔的類似問題的答案,但仍然無法弄清楚。
編輯:我不到一周前才開始學習 Python,另一個答案不夠清楚,無法幫助我。
編輯 2:Nvm,不確定我之前做錯了什么,但是當我再次嘗試時它起作用了。
您可以使用HttpResponseRedirect
:
from django.http import HttpResponseRedirect
# ...
return HttpResponseRedirect('/url/url1/')
其中“url”和“url1”等於重定向的路徑。
從上面的答案中對導入語句的更改提出了一點建議
from django.http import HttpResponseRedirect
return HttpResponseRedirect('/url-name-here/')
你可以試試這個:
from django.shortcuts import redirect
return redirect(f'/customer/{pk}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.