0

I've Images in my project folder created automatically and I want to upload these images to my MySQL DB. These images are named img0.png, img1.png.. etc

What I am currently doing :
views.py

for i in range(imageCount):
    img = open("img%s.png" %i)
    obj = userImages(userId = userid, images=img)
    obj.save()

models.py

class userImages(models.Model):
    userId = models.IntegerField()
    images  = models.ImageField()

This doesn't work. How can I make it work??

Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17
aditya
  • 123
  • 2
  • 11
  • 1
    I'd suggest you to store the file in a different place (like a server, google storage or aws s3) and create a column to keep the path in the db... databases are not so great to keep files... https://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – Caique C Pereira May 20 '20 at 14:18
  • Thanks for the suggestion, but is there any way I can make this work? I want these images to be stored directly in the database. – aditya May 20 '20 at 14:28
  • 1
    I found this https://pynative.com/python-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql/ – Caique C Pereira May 20 '20 at 14:46

1 Answers1

1

Databases are not a good place to put files in, please consider using s3 or cloud.

If you really want to save it on database use BinaryField but as the same django docs is warning you that:

Abusing BinaryField

Although you might think about storing files in the database, consider that it is bad design in 99% of the cases. This field is not a replacement for proper static files handling.

Community
  • 1
  • 1
Paaksing
  • 432
  • 1
  • 4
  • 17