django – why is the request.POST object immutable?

It’s a bit of a mystery, isn’t it? Several superficially plausible theories turn out to be wrong on investigation:

  1. So that the POST object doesn’t have to implement mutation methods? No: the POST object belongs to the django.http.QueryDict class, which implements a full set of mutation methods including __setitem__, __delitem__, pop and clear. It implements immutability by checking a flag when you call one of the mutation methods. And when you call the copy method you get another QueryDict instance with the mutable flag turned on.

  2. For performance improvement? No: the QueryDict class gains no performance benefit when the mutable flag is turned off.

  3. So that the POST object can be used as a dictionary key? No: QueryDict objects are not hashable.

  4. So that the POST data can be built lazily (without committing to read the whole response), as claimed here? I see no evidence of this in the code: as far as I can tell, the whole of the response is always read, either directly, or via MultiPartParser for multipart responses.

  5. To protect you against programming errors? I’ve seen this claimed, but I’ve never seen a good explanation of what these errors are, and how immutability protects you against them.

In any case, POST is not always immutable: when the response is multipart, then POST is mutable. This seems to put the kibosh on most theories you might think of. (Unless this behaviour is an oversight.)

In summary, I can see no clear rationale in Django for the POST object to be immutable for non-multipart requests.

Leave a Comment