5

Django code samples involving post data often shows code similar to this:

if request.method == "POST":
   post = request.POST.copy()
   #do stuff with post data

Is there a reason for copying the post data instead of working with it directly?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Jeff
  • 3,252
  • 3
  • 23
  • 13

1 Answers1

10

I think it is because request.POST itself is defined immutable. If you want a version you can actually change (mutability), you need a copy of the data to work with.

See this link (request.POST is a QueryDict instance).


class QueryDict

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.

Community
  • 1
  • 1
ChristopheD
  • 112,638
  • 29
  • 165
  • 179
  • 2
    +1: And it *must* be immutable so that it can be built lazily. The copy forces getting all the POST data. Until the copy, it may not all be fetched. Further, for a multi-threaded WSGI server to work reasonably well, it's helpful if this is immutable. – S.Lott Feb 26 '10 at 11:18