How to make Django save an image to static folder
10:22 29 Aug 2021

I have a view that receives an image then saves this image in a temp folder. After that, I do some processing in the image and save it in another folder. But I can´t use it because it is not in the static folder of the app it is considered not secure and gives an error message. This code works, but the path is hardcoded.

        img = request.FILES["image"]
        img_extension = os.path.splitext(img.name)[1]

        # This will generate random folder for saving your image using UUID
        save_path = 'D:/Photo/GFPGAN/inputs/whole_imgs'
        if not os.path.exists(save_path):
            # This will ensure that the path is created properly and will raise exception if the directory already exists
            os.makedirs(os.path.dirname(save_path), exist_ok=True)

        # Create image save path with title
        uui = str(uuid.uuid4())
        img_save_path = "%s/%s%s%s" % (save_path, "image", uui, img_extension)
        with open(img_save_path, "wb+") as f:
            for chunk in img.chunks():
                f.write(chunk)
        subprocess.call('python D:/Photo/GFPGAN/inference_gfpgan.py --upscale 2 --test_path D:/Photo/GFPGAN/inputs/whole_imgs --save_root D:/Photo/GFPGAN/results',  shell=True)
        shutil.move('D:/Photo/GFPGAN/results/restored_imgs/image'+uui+'.jpg', 'C:/Users/rapha/OneDrive/Área de Trabalho/Harvard/CSW/commerceTest/cs50-commerceM/auctions/static/auctions/images/images'+uui+'.jpg')

        listing = form.save(commit=False)
        print(img_save_path)
        listing.restoredimage  = 'C:/Users/rapha/OneDrive/Área de Trabalho/Harvard/CSW/commerceTest/cs50-commerceM/auctions/static/auctions/images/images'+uui+'.jpg'
        #listing.restoredimage = cv2.imread("D:/Photo/GFPGAN/results/restored_imgs/image.jpg") 
        listing.restoredimage = 'C:/Users/rapha/OneDrive/Área de Trabalho/Harvard/CSW/commerceTest/cs50-commerceM/auctions/static/auctions/images/images'+uui+'.jpg'
        listing.owner = user
        listing.save()
        return HttpResponseRedirect(reverse("index"))

How can I save the processed image in the correct path?

The error is : Exception Type: SuspiciousFileOperation

python django