How do you fix the following Django Error: “Type: IOError” “Value: [Errno 13] Permission denied”

前端 未结 2 951
眼角桃花
眼角桃花 2021-01-14 17:08

I am following a Django Tutorial where you are required to construct some image thumbnails once an image is saved in admin. I am also using Python\'s tempfile module to save

2条回答
  •  悲哀的现实
    2021-01-14 17:45

    I regret but mikej's answer is not a solution at all as PIL supports both syntax examples. Probably, I copied the same piece of software from somewhere, and it works perfectly on my linux machines but not on windows 7. The reason is not in the image save command but rather in the following one. The command ...

    self.thumbnail.save(thumb_fn, File(open(tf.name)), save=False)

    ... causes the permission denied error because the file is still open and cannot be opened twice at least on windows. The same error can be simulated by

    copyfile(tf2.name,"some-new-filepath")
    

    A proper workaround is

    1. Create a temporary file that is not deleted when closed
    2. Save and close the thumbnail
    3. Remove the temporary file manually

    This works no matter how you save the thumbnail.

    tf = NamedTemporaryFile(delete=False)
    im.save(tf.name, "PNG")
    #im.save(tf, "PNG")
    tf.close()
    copyfile(tf.name,"some-new-filepath")
    os.remove(tf.name)
    

提交回复
热议问题