Valueerror: I/O Operation on Closed File. Python, Django, Boto3
I Have a Post Method in My Views. Py: Def Post(Self, Request): Author = User. Objects. Get(Id=Request. Data. Get('User_Id')) New_Article = Article. Objects...
I have a post method in my views.py :
def post(self, request):
author = User.objects.get(id=request.data.get('user_id'))
new_article = Article.objects.create(author=author, title=request.data.get('title'),
text=request.data.get('text'),img=File(request.data.get('image[0]')))
new_article.save()
for i in range(20):
img_key = 'image[{}]'.format(i)
img = request.data.get(img_key)
if img:
article_img = ArticleImage(article=new_article,img=File(img), is_main=False )
article_img.save()
else :
break
images = ArticleImage.objects.filter(article=new_article)
return Response({
'article': ArticleSerializer(new_article, context=self.get_serializer_context()).data
})
It creates a new article which contains img files. The image files I save in AWS S3 bucket . Saving main image of article using new_article.save() method works fine , but article_img.save() returns an error:
**File "C:\Users\Arcvi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\storages\backends\s3boto3.py", line 520, in _save_content content.seek(0, os.SEEK_SET)*
***ValueError: I/O operation on closed file.****
I guess I do something wrong in my for loop. If you need more information about code , I will share it . Please any help.
2 Answers
Try maybe to open this file and then create django File object.
img = request.data.get(img_key)
if img:
with open(img.file.seek(0), "rb") as opened_image:
article_img = ArticleImage(article=new_article,img=File(opened_image), is_main=False )
article_img.save()
This might sound obvious but
ValueError: I/O operation on closed file.
Means the file you are working with has closed. If it's a Python PIL image, you can run yourimage.verify().
Once you save (ex: new_article.save()), files become closed. Ex: new_article.img.closed equals True.
This happened to me when overriding a Django ModelForm save method. I overcame it by setting commit equals False. The file will stay opened until you finally save.