0

I have few questions please guide on these

  1. I am try to stroe images in database but they are getting store in media directory 2.The corresponding url is stored in the db column but I need actual image to be stored in the db
    please advice
  • Why do you need to save images into the database? Best way to do: Though File System comes with some cost and certain cons, A good Internal Folder Structure and choosing a folder location which may be a little difficult to access by others. – Akash Joshi Oct 13 '20 at 12:29
  • if store images through filesystem , suppose system crash than we lose all the data – Nitesh chahar Oct 13 '20 at 13:23
  • added in the answers you can check – Akash Joshi Oct 13 '20 at 13:29

2 Answers2

1

This is not a good idea to store an image in DB instead media folder. But you can use BinaryField for this:

model.py

class MyModel(model.Model):
    image = models.BinaryField(blank=True)

view.py

def image(request):
    image_file = request.FILES['image_file'].file.read()
    MyModel.objects.create(image=image_file)
Akash Joshi
  • 106
  • 6
0

It is not possible to store the image itself in a database. You need to convert it to binary and store. You can use BytesIO. Here is a link which similar question explaining how to use it

How to write PNG image to string with the PIL?