python loop until length

Viewed 40

so I'm having trouble getting some data to my DB. I'm not that good with python and trying to learn.

so this is the data I'm sending to the Django server:

enter image description here

enter image description here

as you can see I'm getting FILES called doc[i] to the server and I want to save the name of the file in the DB. but I don't know how to loop through it.

that's what I'm doing for now:

def submit_quality_dept_application(request, application_id):
doc0 = request.FILES['doc0']
length = request.data['length']
application = Application.objects.get(id=application_id)
application_state = application.application_state
application_state['doc0'] = doc0.name
Application.objects.filter(id=application_id).update(
    application_state=application_state)
return Response(length, status=status.HTTP_200_OK)

that way it's working for doc0 and I can save its name in the DB. but I want to loop through every doc[i] and save it in DB.

any suggestions?

1 Answers

You can enumerate over the items with a range(…) [Python-doc]:

def submit_quality_dept_application(request, application_id):
    n = int(request.data['length'])
    application = Application.objects.get(id=application_id)
    application_state = application.application_state
    for i in range(n):
        doc = request.FILES[f'doc{i}']
        application_state[f'doc{i}'] = doc.name
    Application.objects.filter(id=application_id).update(application_state=application_state)
    return Response(length, status=status.HTTP_200_OK)

But I'm not sure if the is the best way to handle multiple files. It might be better to submit a list of files as request, for example for the same key.

Related