[Solved]-Reading multidimensional arrays from a POST request in Django

6👍

This is related with that question. As stated there, I made special library for Django/Python to handle multidimensional arrays sent through requests. You can find it on GitHub here.

👤berni

7👍

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

4👍

Does this help? http://dfcode.com/blog/2011/1/multi-dimensional-form-arrays-and-django/

If you want POST data, the only way to get it is to specify the exact ‘name’ you are looking for:

    person[1].name = request.POST['person[1][name]']
    person[1].age = request.POST['person[1][age]']
    person[2].name = request.POST['person[2][name]']
    person[2].age = request.POST['person[2][age]']

Here is a quick on-the-fly workaround in Python when you have the need to extract form values without explicitly typing the full name as a string:

    person_get = lambda *keys: request.POST[
        'person' + ''.join(['[%s]' % key for key in keys])]

Now when you need information, throw one of these suckers in and you’ll have much wider flexibility. Quick example:

    person[1].name = person_get('1', 'name')
    person[1].age = person_get('1', 'age')
    person[2].name = person_get('2', 'name')
    person[2].age = person_get('2', 'age')

Leave a comment