QueryDict getlist returns empty list - django

I'm sending from frontend object with one property which equal to array.
In backend I need to get data from that array.
when i write request.POST i see:
<QueryDict: {u'response[0][doc_id]': [u'14'], u'response[1][uuid]': [u'157fa2ae-802f-f851-94ba-353f746c9e0a'], u'response[1][doc_id]': [u'23'], u'response[1][data][read][user_ids][]': [u'9'], u'response[0][uuid]': [u'8a0b8806-4d51-2344-d236-bc50fb923f27'], u'response[0][data][read][user_ids][]': [u'9']}>
But when i write request.POST.getlist('response') or request.POST.getlist('response[]') i get
[]
request.POST.get('response') doesn't work as well (returns None).
What is wrong?

Because you don't have either response[] or response as keys, you have the literal strings response[0][doc_id] and response[1][uuid] etc.
If you want to use a structure like this, you should send JSON rather than form-encoded data and access json.loads(request.body).

Related

Why Is My Django Post Request Sending Incorrectly Parsed My List of Dictionaries?

Here is my Django view:
def sendMail(request):
url = 'https://example.com/example'
dictwithlist = request.FILES['dictwithlist']
parsed = json.load(dictwithlist)
// the log file shows that the lists are intact after json.loads
logip(request, json.loads(parsed))
x = requests.post(url, json.loads(clockoutJSON))
return HttpResponse(status=204)
If I just send parsed data my express server receives an empty dict, {}. When I log the json.loads(parsed) I find good data, with the lists intact. When the data gets to the other side though, the dictionaries inside the nested list are all removed, replaced by only strings of their keys.
I tried using headers as described here: Sending list of dicts as value of dict with requests.post going wrong but I just get 500 errors. I don't know if I'm formatting the headers wrong or not. (because the code has line spacing and I'm copying it)
Can anyone help me understand why this is failing? I need that list to get through with its dictionaries intact.
I believe you may need to use dumps rather than loads when sending the request:
x = requests.post(url, json.dumps(parsed))
Alternatively if you're using the python requests library you can send json as a dict as below:
response = requests.post(url=url, json=parsed)

what's the value type of the value of request.POST in django?

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?
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.

How can i pass empty array for specific field in postman (form-data)?

I'm using laravel framework and need empty array to do some actions, and my request is Post with form-data. i dont't want it JsonRequest i want empty array with form-data request. please help.
I'm trying with above, but its returning null, i want empty array.
What i want in backend is [ ] empty array.
hi you can use null value instead of an empty array
when you want send a array for example you send key[index] : value
for a null value you should send just key without bracket and value with empty string for example key : "" or key : in postman

Accessing request parameters django

Hi I am trying to capture sms parameters from a request that comes in this format
b'name=kcom-sms04&number=%2B255688121131&content=Hello'
Above appears when I print HttpRequest.body
How can I access number, content and name parameters? I use django.
Short answer: use request.POST.
Normally these are POST parameters, you can access these with request.POST [Django-doc], which is a QueryDict [Django-doc]. A QueryDict is a dictionary-like object, but where a key can map to multiple values.
For example, you can access 'kcom-sms04' with request.POST['name'].

Trying to create an object from django models after loading data with json, but I get 'TypeError: __init__() keywords must be strings'

I retrieved data from the API of a website and deserialized them using json.loads(some_data).
Json returns a dictionary that contains 'u' before each key and value like that:
data = {u'y_coordinate': u'1902125', u'case_number': u'HW301956', u'domestic': False}
Now I would like to instantiate an object from the Django models by doing:
obj = Model(**data)
However, I get 'TypeError: init() keywords must be strings'
So I was wondering if the problem comes from the 'u' in front of the keys and value, and if it is, how can I get rid of it in order to create the object?
I understand that I can write a function that would loop through the data and get rid of the 'u' whenever it encounter the character, but is there a more efficient way to do it?
You need to iterate over the dictionary, encoding the key whenever it is a unicode.
>>> {key.encode('utf8') if isinstance(key, unicode) else key:value for (key, value) in data.iteritems()}
{'y_coordinate': u'1902125', 'domestic': False, 'case_number': u'HW301956'}