Liorsion
Liorsion

Reputation: 582

Reading multidimensional arrays from a POST request in Django

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

friends[0][id]    12345678 
friends[0][name]  Mr A
friends[1][id]    78901234
friends[1][name]  Mr B

That is, an array of two items, name and id.

Is there an automatic way to receive this input as list or a dictionary? I can't seem to be able to make .getlist work

Upvotes: 12

Views: 8995

Answers (3)

Herman Schaaf
Herman Schaaf

Reputation: 48445

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

Upvotes: 7

berni
berni

Reputation: 1975

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.

Upvotes: 6

DrMeers
DrMeers

Reputation: 4207

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')

Upvotes: 4

Related Questions