How to display image file from sftp remote server in django template?

  1. We have 2 servers. One of them is for media files and the other one is for django project server(ngnx+gunicorne).
  2. Our media server is local(internal). We want to access to media server from inside the project with sftp storage package which includes paramiko. we don't want to access media server via URL (http,https).
  3. HttpResponse(file, content_type=type) can display the image file as a big picture but we want to pass the image file to django template for display in html file like <a href="{{ course.get_absolute_url }}"><img src="{{images}}" alt=""></a>
  4. We know HttpResponse is not a good solution but we use it below code for explained our problem.
# view
def coursesPageView(request):
    courses = Course.objects.filter(is_published=True)
    image_data =[imageRespone(data) for data in courses]

    data = {
            'images' : image_data
    return render(request, 'pages/course2.html', data)

def imageRespone(valid_image):
    if sfs.exists(
        file = sfs._read(
        type, encoding = mimetypes.guess_type(        
        response = HttpResponse(file, content_type=type)
        return response
        return HttpResponse('404 Not Found')
 <a href="{{ course.get_absolute_url }}"><img src="{{images}}" alt=""></a>

What you can do is mounting a shared drive into your webserver pointing to your media server (Samba for linux). Then with Django you can specify the localisation of your statics file.

For example :

import os

MEDIA_URL        = "/media/"
MEDIA_ROOT       = os.path.abspath(os.path.join(os.sep, 'srv', 'media'))

STATIC_URL       = '/app/static/'
STATIC_ROOT      = os.path.abspath(os.path.join(os.sep, 'srv', 'static'))

Pay attention to the permissions between the web server and the mounted folder.

Back to Top