Static media images are not displaying in Django

models.ImageField – these are media files, not static.

They get affected by settings: MEDIA_ROOT, MEDIA_URL

What the docs say about MEDIA_ROOT:

Absolute filesystem path to the directory that will hold user-uploaded files.

Warning

MEDIA_ROOT and STATIC_ROOT must have different values.

And media files should not be mixed with static files in folders.

Media files should be referenced like that

<img src="{{ item.image.url }}" />

here image – your field name, for image2 it would be item.image2.url

You have mixed static and media files by these field options:

image = models.ImageField(upload_to='static/media',blank=True)
image2 = models.ImageField(upload_to='media/%Y/%m/%d',blank=True)
image3 = models.ImageField(upload_to='media/%Y/%m/%d',blank=True)

now some of media files (image2, image3) are reachable through MEDIA_URL (because they belong to MEDIA_ROOT folder), some (image) are not – because they belong to STATIC_ROOT folder. You have found a workaround – you reference image field by "{% static item.image %}" trick which can help overcoming wrong setup but is also not a right way.

Also, your teammate might be having troubles with accessing “static” files because the term static is being misused. Again, files stored in the ImageFields are not static and are not part of your project. They are supposed to be uploaded by users and never stored in git. If you want to share them – you have to share files already uploaded to your local /media/... folders somehow.

Static files are/can be something like:

  • favicon.ico
  • main.css
  • robots.txt
  • popup.js
  • top_banner.jpg

So:

  • change upload_to for image field
  • move already uploaded files to new folder (under media folder), update file paths in the db
  • fix the way you reference these media files in templates to ...image.url

see also:

Leave a Comment