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

后端 未结 1 529
南笙
南笙 2020-12-03 04:51

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:<

相关标签:
1条回答
  • 2020-12-03 05:14

    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))
    
    0 讨论(0)
提交回复
热议问题