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
-
Please add more details. Where does the file that has to be saved come from? Which database record do you have to save to?utkbansal– utkbansal2017-01-08 13:13:55 +00:00Commented Jan 8, 2017 at 13:13
-
Okay, if you need any more info, let me know :)Jude Molloy– Jude Molloy2017-01-08 13:15:59 +00:00Commented Jan 8, 2017 at 13:15
-
Why dont you just run a simple query?utkbansal– utkbansal2017-01-08 13:21:09 +00:00Commented Jan 8, 2017 at 13:21
-
The images aren't in the database yet, I'm trying to get them in.Jude Molloy– Jude Molloy2017-01-08 13:22:18 +00:00Commented Jan 8, 2017 at 13:22
-
You could write a script to insert images in your table.utkbansal– utkbansal2017-01-08 13:23:38 +00:00Commented Jan 8, 2017 at 13:23
|
Show 1 more comment
1 Answer
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')))
2 Comments
Jude Molloy
Will I have to write that line of code for every item in the folder?
utkbansal
No you could put this in a loop and run it for all files in the folder.