Django Loop to Update Multiple Objects Django.How

Author avatar wrote on 03/06/2022

Set filed name this way name=”sub_service_{{ service.id }}”

In View data will be the name fo the field in the loop, request.POST[data] is the value

for data in request.POST:
        if "sub_service_" in data:
            sub_service_id = int(data.replace("sub_service_", ""))
            CompanySubService.objects.select_for_update().filter(id=sub_service_id).update(delivery_per_hour = request.POST[data])

Example with try and message

if request.POST.get("form_type") == 'update_sub_services_delivery':
    try:
        for data in request.POST:
            if "sub_service_" in data:
                sub_service_id = int(data.replace("sub_service_", ""))
                CompanySubService.objects.select_for_update().filter(id=sub_service_id).update(delivery_per_hour = request.POST[data])
        messages.success(request, "Sub services delivery info has been updated." )
    except Exception as e:
        print("Exception update_sub_services_delivery ==========================")
        messages.error(request, "Error. Something went wrong.")
        print(e)
        print("End of Exception  ==========================")
        
    return render(request, template_name, context)

CRUDgen Django CRUD generator