Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove key from request QueryDict in Django?

Tags:

python

django

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?

like image 222
Dmitry Avatar asked Apr 07 '15 13:04

Dmitry


2 Answers

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.

like image 66
Daniel Roseman Avatar answered Oct 24 '22 00:10

Daniel Roseman


@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().

like image 27
Mandemon Avatar answered Oct 23 '22 23:10

Mandemon