Reading multidimensional arrays from a POST request in Django

前端 未结 3 2080
抹茶落季
抹茶落季 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:16

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

提交回复
热议问题