I ended up doing a redirect instead. That removes the get parameter.
How to remove get parameter from url in django view
-
29-06-2022 - |
Question
I have the following view:
def copy_group(request):
copy = request.GET.get('copy','')
if copy:
#do my copy process
context = {'view':'copy-view'}
return render(request, 'groups/copy-view.html', context)
This invoked with the following url mysite.com/groups/?copy=1
The problem is that if I refresh the page, my process keeps copying over and over.
How can I remove the ge parameter so the url returns after it copies: mysite.com/groups/
I tried inserting this in my view code:
request.GET.pop('copy')
But I get the error: This QueryDict instance is immutable
Solution 2
OTHER TIPS
If I understand it well, once you've done the copy you want the page to be redirected so no more copy will be made. Do like this then:
...
if copy:
the actual copy and then...
return HttpResponseRedirect(redirect_to='/the-path-without-copy-parameter/')
...
Then you can improve your code:
- add copy as an actual route parameter, def copy_group(request, copy=None)
- generate the path in redirect_to instead of hardcoding it
- Out of topic: add a functional test for it if there is none :)
BTW, I'm not sure why you use a Get parameter and not just a different URL for it??
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow