4

I am trying to extract a posted array in Django 2.

I am posting the following:

sprints[0][id]: 5
sprints[0][name]: Test sprint 1
sprints[0][order]: 0
sprints[0][project]: 
sprints[0][start]: 
sprints[0][end]: 
sprints[1][id]: 6
sprints[1][name]: Test sprint 2
sprints[1][order]: 1
sprints[1][project]: 
sprints[1][start]: 
sprints[1][end]: 

This returns the data visibly

def single(request, id):
    return Response(request.POST)

However this return it as an empty list ([]).

def single(request, id):
    return Response(request.POST.getlist('sprints'))

As does this.

def single(request, id):
    return Response(request.POST.getlist('sprints[]'))

Why?

ggdx
  • 3,024
  • 4
  • 32
  • 48
  • The bracket notation is meaningless and comparable to any other character, like `sprints-0-id=5&sprints-0-name=…`. It’s just a list of key/value pairs and none of the keys are `sprints` or `sprints[]`. You’ll have to parse it yourself or find some library. – Ry- Apr 13 '18 at 11:25
  • @Ry︁ It would be no different than posting an array of checkbox values, no? It is form data (posted from a VueJS frontend) – ggdx Apr 13 '18 at 11:26
  • What’s an array of checkbox values? Checkboxes each have a name. You can give multiple checkboxes the same name, in which case they’ll be posted in the format `name=value1&name=value2&name=…` and `request.POST.getlist('name')` will return `['value1', 'value2', …]`. – Ry- Apr 13 '18 at 11:28
  • If it’s coming from JavaScript and it’s a POST request (or any other request with a body), I would highly recommend JSON for this kind of arbitrarily nested structure. – Ry- Apr 13 '18 at 11:28
  • @Ry︁ That was the issue, POST (specifically PUT in this case) data was being sent as a string instead of JSON because of Axios javascript lib using bad config. There wasn't really anything wrong with the python. If you want to pop your comment as an answer, I'll mark it as correct. – ggdx Apr 13 '18 at 12:12

0 Answers0