Search code examples
djangoimagedjango-templatesabsolute-path

Django - absolute path image not showing up


I am trying to display an image with the src equal to an absolute path. This is what I did in the template

    <img src="/home/userName/Documents/app/userPhotos/1/uploadedPhotos/imageName.png" alt="" />

and it does not show up. I'm positive that it is the correct absolute path. Is there anything I need to do, say in my settings.py file, to be able to use absolute paths? Do I need to

import os

in my template?

Edit:

Just in case it helps, when I run the server and go to the url which calls the template (/displayImages/, this is what it says in my terminal:

[23/Feb/2014 12:07:27] "GET /displayImages/ HTTP/1.1" 200 413
[23/Feb/2014 12:07:27] "GET /home/userName/Documents/app/userPhotos/1/uploadedPhotos/imageName.png HTTP/1.1" 404 2993

Solution

  • As Daniel wrote in his answer, you should not use absolute path for any content on your website. This leads to a security concern and to a not working statement position. When the browser sees /absolute/path/img.png, it searches for this path starting at the root of your website. So, this can become /home/userName/Documents/app/absolute/path/img.png, which doesn't exists.

    The right way is:

    • Read the doc :)
    • Add (or use) the settings.STATIC_URL defined in settings.py. The default path is the folder static/ in your app folder.
    • Use {% load staticfiles %} and {{ static "relative/path/file.ext" }} in your template