1

I am building a Django application that stores image files in a mongodb GridFS.

I use Djongo to work with the database and followed this example https://www.djongomapper.com/using-django-with-mongodb-gridfs/ to store the images to the DB.

now I can, currently through the admin page, upload images to the DB, which need to be accessed using a URL like this:

http://127.0.0.1:8000/files/60fae4884db41b9ad761c8b0

Now I have this in the urls.py

urlpatterns = [
    ...
    path('files/<str:fileid>', views.files, name='files'),
]

But in View file I don't know how to retrieve the image from the DB:

@login_required
def files(request, fileid):

    return response

I searched the documentation of Djongo and Django but couldn't find an easy way to do it.

Note: In the main DB collection only the image file name is stored. In gridfs collection 'files' an ID (the one in the URL), the image name (the only link to the main collection) and other details are stored. And in the 'chunks' collection there is an ID, a files_ID (foreign key to the files ID) and the binary data.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Fahad Alduraibi
  • 372
  • 6
  • 17

1 Answers1

1

You shouldn't serve the files using Django, you need to set MEDIA_URL and makes it point to your web server e.g. NGINX and use nginx-gridfs module to serve the file.

This apply to all types of storage, serving static files should not be done through Django, its the job of the web server.

Reference Check the warning under "Storage" section

rayed
  • 597
  • 4
  • 10
  • Two questions: 1- Can I do this with apache? Since it is my web server. 2- Can I enforce the same authentication i use in my app when files are accessed in this way? – Fahad Alduraibi Jul 24 '21 at 09:52
  • 1- Not sure about Apache. 2- you can use a Nginx module http://nginx.org/en/docs/http/ngx_http_secure_link_module.html this will make the request go to Django which will forward it to Nginx with a secure link that expire after few seconds – rayed Jul 24 '21 at 10:09