1

I have a database model that in the Django model all I need to do is upload an image file to a new database record. Is there anyway I can automate this as I have a lot of images to upload? All images will come from a folder on my computer and each picture will be added to a new database record. All help is appreciated. Thanks

6
  • Please add more details. Where does the file that has to be saved come from? Which database record do you have to save to? Commented Jan 8, 2017 at 13:13
  • Okay, if you need any more info, let me know :) Commented Jan 8, 2017 at 13:15
  • Why dont you just run a simple query? Commented Jan 8, 2017 at 13:21
  • The images aren't in the database yet, I'm trying to get them in. Commented Jan 8, 2017 at 13:22
  • You could write a script to insert images in your table. Commented Jan 8, 2017 at 13:23

1 Answer 1

3

Just run a simple script to save files stored in a particular folder

from django.core.files import File

class MyModel(models.Model):
    picture=models.ImageField()


MyModel.picture.save('abc.png', File(open('/tmp/pic.png', 'r')))

To do this for all files in a directory -

BASE_PATH = '/home/somefolder' 
files = os.listdir(BASE_PATH)
for file in files:
    MyModel.picture.save(file, File(open(os.path.join(BASE_PATH, file), 'r')))
Sign up to request clarification or add additional context in comments.

2 Comments

Will I have to write that line of code for every item in the folder?
No you could put this in a loop and run it for all files in the folder.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.