Reading multidimensional arrays from a POST request in Django

前端 未结 3 2081
抹茶落季
抹茶落季 2021-02-08 04:53

I have a jquery client that is sending a POST request with a multidimensional array, something like this:

friends[0][id]    12345678 
friends[0][nam         


        
3条回答
  •  终归单人心
    2021-02-08 05:22

    DrMeers' link is no longer valid, so I'll post another method of achieving the same thing. It's also not perfect, and it would be much better if Django had such a function built-in. But, since it doesn't:

    Converting Multi-dimensional Form Arrays in Django

    Disclaimer: I wrote that post. The essence of it is in this function, which could be more robust, but it works for arrays of one-level objects:

    def getDictArray(post, name):
        dic = {}
        for k in post.keys():
            if k.startswith(name):
                rest = k[len(name):]
    
                # split the string into different components
                parts = [p[:-1] for p in rest.split('[')][1:]
                print parts
                id = int(parts[0])
    
                # add a new dictionary if it doesn't exist yet
                if id not in dic:
                    dic[id] = {}
    
                # add the information to the dictionary
                dic[id][parts[1]] = post.get(k)
        return dic
    

提交回复
热议问题