我有一个带有视图(url)的 django 应用程序,它显示不同位置的不同列表:
path('ItemList/<int:locationId>/', views.ItemList, name="ItemList"),
path('SomethingList/<int:locationId>/', views.SomethingList, name="SomethingList"),
然后在模板中我有一个菜单,当我可以在位置之间切换时,即。在 -- ItemList/2/ 中我可以切换到具有不同 ID 的位置 或者在 SomethingList/4/ 中我可以切换到具有不同 ID 的位置
要切换位置,我有一个方法(显然是不正确的):
def setLocation (request, newLocationId):
return redirect(request.META['HTTP_REFERER'], locationId = newLocationId)
但是我该怎么做,才能获取当前的网址,例如: 物品清单/2/ 并将其重定向到 ItemList/4/ (即不同的 id?)
该请求有一个
resolver_match
属性,您可以将其与新位置 ID 一起使用来获取要重定向到的 url:
def setLocation (request, newLocationId):
url_name = request.resolver_match.url_name # "ItemList" or "SomethingList" as per URL conf
return redirect(reverse(url_name, kwargs={"locationId": newLocationId}))