Search code examples
djangodjango-databasedjango-file-upload

How can I upload files into django database


I want to upload files to the database that Django use, I know that I can do it through forms, but I want to read the files in my files system get the path of the docx or pdf and uploaded it into the database, how can I do that Here is the code that i use to get the path of the files in my filedsystem

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)

Solution

  • You can use ContentFile for this.

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