Home > Mobile >  How to get all files from a specific folder and store them in DB, django
How to get all files from a specific folder and store them in DB, django

Time:10-30

class Documents(models.Model):
   file = models.FileField()

I have got a folder called media in the root. It contains multiple files (pdf's). Can I automatically store them in the table called Documents.

Thank you so much!

CodePudding user response:

I found already an answer

import os

for filename in os.listdir("..."):
    if filename.endswith(".pdf"): 
        Documents.objects.create(file=filename)
    else:
        continue

CodePudding user response:

I do not know a direct link between files in a filesystem and a django model filefield but you can get all files in a tree (even recursiv) and loop through them e.g.:

path = 'C:/ ....'
file = '*.txt'

for file in glob.glob(os.path.join(path, file), recursive = True):
    # here create file entry in your model

maybe this helps

  • Related