Home > Software engineering >  what's the value type of the value of request.POST in django?
what's the value type of the value of request.POST in django?

Time:12-25

This is from print(request.POST)

<QueryDict: {'csrfmiddlewaretoken': ['2Tg4HgJ07qksb3hPUDWSQYueYOjYOkQcmzll9fnjbJ0GZHkWHdM8DtYqZB4uv3Fv'], 'username': ['boycececil'], 'password': ['password']}>

This is from print(request.POST.get('username'))

boycececil

So as you can see, list (from one of the values of QueryDict)-> string(from the get function), that's magic! Isn't it?

So, somebody know what's going on?

CodePudding user response:

What the value type of the value of request.POST in django?

The type is django.http.request.QueryDict

So as you can see, list -> string, that's magic! Isn't it?

No, it isn't magic. This is just the documented behavior of QueryDict:

"QueryDict.__getitem__(key)

Returns the value for the given key. If the key has more than one value, it returns the last value. ..."

Note: if you want all values for a key, you can call getlist(key) on the QueryDict.


So, the request.POST is a subclass of the dictionary but not a raw dictionary.

It is a subclass of the django MultiValueDict class which is a subclass of dict.

When I call get(key) to the Querydict it return the last value of the list. Sounds like the get method in Querydict overwrite the get method in the raw dictionary.

Yes ... that is what the __getitem__ method does.

By the way, I wonder why we need multiple value for one key.

It is because HTTP allows multiple values for a given parameter in a request. So if multiple values can be provided, django need to be able to make them available via the HttpRequest.POST object.

But since this is an unusual case, they decided to just give your code one value for each parameter ... unless it specifically asks for them all. Django is being helpful.

  • Related