0

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)
AshMGM
  • 53
  • 8

1 Answers1

0

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()))
SHIVAM JINDAL
  • 2,844
  • 1
  • 17
  • 34
  • Thak you, It´s works, but I have a doubt, when i put the file name, my file its saved with the name I put and the database add into it other words, how can I avoid that. original `file name:work.docx` `djando database name:work_9Btchte.docx ` – AshMGM May 08 '18 at 14:25
  • @AshMGM Django append a random string in filename to ignore the duplicate file issue. – SHIVAM JINDAL May 08 '18 at 16:52
  • Theres a way to only store the file in the database but not in my filesystem ? – AshMGM May 18 '18 at 20:33