How to assign a local file to the FileField in Django?

旧街凉风 提交于 2019-11-26 20:21:01

问题


I was trying to assign a file from my disk to the FileField, but I have this error:

AttributeError: 'str' object has no attribute 'open'

My python code:

pdfImage = FileSaver()
pdfImage.myfile.save('new', open('mytest.pdf').read())

and my models.py

class FileSaver(models.Model):

    myfile = models.FileField(upload_to="files/")

    class Meta:
        managed=False

Thank you in advance for your help


回答1:


Django uses it's own file type (with a sightly enhanced functionality). Anyway Django's file type works like a decorator, so you can simply wrap it around existing file objects to meet the needs of the Django API.

from django.core.files import File

local_file = open('mytest.pdf')
djangofile = File(local_file)
pdfImage.myfile.save('new', djangofile)
local_file.close()

You can of course decorate the file on the fly by writing the following (one line less):

pdfImage.myfile.save('new', File(local_file))


来源:https://stackoverflow.com/questions/3501588/how-to-assign-a-local-file-to-the-filefield-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!