5

Earlier I was using default database sqlite3, but today i've changed it to postgresql.

I wants to save the image files in database not in project directory itself. How can I do that?

Dave
  • 7,555
  • 8
  • 46
  • 88

1 Answers1

10

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)
amarynets
  • 1,765
  • 10
  • 27
  • 2
    Why `BinaryField` not `ImageField` ? What are pros and cons of using `ImageField` ? – MD. Khairul Basar Sep 28 '17 at 04:34
  • 3
    @MD.KhairulBasar An ImageField is simply a text field that stores the file name only. – Selcuk Sep 28 '17 at 04:39
  • 1
    Because of ImageField store images in `MEDIA_ROOT` folder, BinaryField in DB. TS wanna use BD for it. https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.FileField.storage – amarynets Sep 28 '17 at 04:40
  • Thanks. Got it. :D – MD. Khairul Basar Sep 28 '17 at 04:41
  • @Selcuk Sir, it's not just storing the file name, It's storing the entire file in same folder as that of Project. Will it slow down the processes? –  Sep 28 '17 at 04:49
  • @user8557845 Yes, and you will have cacheability issues as those images can only be served through Django and not using a web server, such as nginx. – Selcuk Oct 01 '17 at 04:31