如何将本地文件分配给Django中的FileField? [英] How to assign a local file to the FileField in Django?

查看:726
本文介绍了如何将本地文件分配给Django中的FileField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



AttributeError:'str'对象没有属性'open'



我的python代码:

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

和我的models.py

  class FileSaver(models.Model):

myfile = models.FileField(upload_to =files /)

class Meta:
managed = False

提前感谢您的帮助

解决方案

Django使用它自己的文件类型(具有视觉增强功能)。无论如何,Django的文件类型类似于装饰器,因此您可以将其围绕现有文件对象进行包装满足Django API的需要。

 从django.core.files导入文件

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

您当然可以通过编写以下内容(一行少一行)来装饰文件:

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


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

解决方案

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))`.

这篇关于如何将本地文件分配给Django中的FileField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆