Django view to redirect to same url with different parameter?

I've got django app with a views (urls), that show different lists for different locations:

path('ItemList/<int:locationId>/', views.ItemList, name="ItemList"),
path('SomethingList/<int:locationId>/', views.SomethingList, name="SomethingList"),    

and then in a template I've got a menu, when I can switch between locations, ie. being in -- ItemList/2/ I can switch to location with different Id or being in SomethingList/4/ I can switch to location with different Id

To switch location, I've got a method (which obviusly is incorrect):

def setLocation (request, newLocationId): 
    return redirect(request.META['HTTP_REFERER'], locationId = newLocationId)

but how can I do it, to get the current url like: ItemList/2/ and redirect it to ItemList/4/ (ie. to different id?)

The request has a resolver_match attribute which you could use together with the new location id to get the url to redirect to:

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}))

ResolverMatch

Вернуться на верх