14

I want to change request.GET querydict object in django. I tried this but changes made by me are not reflected. I tried this

tempdict = self.request.GET.copy() # Empty initially
tempdict['state'] = ['XYZ',]
tempdict['ajaxtype'] = ['facet',]
print self.request.GET

I get

<QueryDict: {}> as my output

Is it possible to change the request.GET querydict object in django?

djvg
  • 11,722
  • 5
  • 72
  • 103
Anurag Sharma
  • 4,839
  • 13
  • 59
  • 101

2 Answers2

22

You can't change the request.GET or request.POST as they are instances of QueryDict which are immutable according to the docs:

QueryDict instances are immutable, unless you create a copy() of them. That means you can’t change attributes of request.POST and request.GET directly.

Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
8

Your code should work if you add one little step: you are now making a copy of the request.GET, but you have not assigned it back to the request. So it is just a standalone object which is not related to the request in any way.

This would the the necessary improvement:

tempdict = self.request.GET.copy()
tempdict['state'] = ['XYZ',]
tempdict['ajaxtype'] = ['facet',]
self.request.GET = tempdict  # this is the added line
print(self.request.GET)

I have tested it in writing custom middleware, but I assume it works the same way in all places.

Eerik Sven Puudist
  • 2,098
  • 2
  • 23
  • 42