Here is one of my Django views:
def index(request):
message = request.GET.get('message', '')
context = RequestContext(request, {
'message': message
})
return render(request, 'bets/index.html', context)
My goal is to display message in template only once, and not to display it on page reload. I tried this:
request.GET['message'] = ''
but get error "This QueryDict instance is immutable". How do I remove key from QueryDict?
Even if you could remove that value from the querydict, that wouldn't help because it is based on the URL you've used to request that view, so when you refresh you're going to be using the same URL again with the existing parameters.
Rather passing the message value in the GET parameters, put it in the session, and use request.session.pop('message')
in the index view.
Even better, use the built-in messages framework which does all that for you.
@Daniel Rosemans answer is correct, in that you should use session to store value.
However, to answer your original question in regards how to remove, GET and POST parameters are immutable. You can not change these querydicts. If you want to remove something from them (say, to prevent key from being iterated over) you need to make copy of the QueryDict and then pop item from it.
https://docs.djangoproject.com/en/3.1/ref/request-response/#querydict-objects
The QueryDicts at request.POST and request.GET will be immutable when accessed in a normal request/response cycle. To get a mutable version you need to use QueryDict.copy().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With