如何将文件上传到django数据库

How can I upload files into django database

我想上传文件到Django使用的数据库,我知道我可以做到 通过表格,但我想读取文件系统中的文件获取 docx 或 pdf 的路径并将其上传到数据库中,我该怎么做 这是我用来获取我的文件系统中文件路径的代码

for dir_, _, files in os.walk(superpath):
    for fileName in files:
        print fileName
        if fileName.find('~$')==-1:
            relDir = os.path.relpath(dir_, superpath)
            if relDir=='.':
                relFile =os.path.join(superpath, fileName)
            else:
                relFile = os.path.join(superpath,os.path.join(relDir, fileName))
                path.append(relFile)

您可以为此使用 ContentFile。

from django.core.files.base import ContentFile
f = open(file_path, 'r')
object.image.save('image.jpg', ContentFile(f.read()))