Post LIST OF OBJECTS from HTML/axios with multipart/form-data to DRF multipart parser

烈酒焚心 提交于 2021-01-28 12:09:25

问题


This is my serializer:

class ParentSerializer(serializers.ModelSerializer):
    children = ChildSerializer(many=True)  # reverse FK relation

ParentSerializer also has an image field, so the request has to be multipart/form-data to support both image and data in a single request.

The following code/test works fine:

test_data = QueryDict('', mutable=True)
dictionary = {
    'name': ['test'],
    'children[0]': [{'key1': 'val1', 'key2': 'val2'}]
}
test_data.update(MultiValueDict(dictionary))

test_serializer = self.get_serializer(data=test_data)
test_serializer.is_valid(raise_exception=True)
test_instance = test_serializer.save()

...because I'm manually creating the children list.

The problem is I'm not able to do the same through axios/HTML form. The data being sent is converted to string.

What are my options? I want to send list of child objects along with other data.

DRF v3.9 & Django v2.2.


回答1:


Your fields must be named in the following form children[0]key1, children[0]key2, children[1]key1, children[1]key2

Note that there is no dot . between the ] and the key name



来源:https://stackoverflow.com/questions/56908497/post-list-of-objects-from-html-axios-with-multipart-form-data-to-drf-multipart-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!