0

I have the following structure

my app/
|_my_app/
|  |_templates/
|_static/
|_media/
|_utils/
|_main.py
|_manage.py
|_.gitignore

and having the in template.html

<img src="./media/image.png"> then it casts a GET 404 error Cannot find /media/image.png.

I have also tried relative path (relative to the template i.e <img src="../../media/image.png">.

Moving the media folder into static (and including {% load static %} I can do

<img src="{% static '/media/image.png'">

without any issues.

  1. Why can't it find ./media/image.png in the first part?
  2. Is there a way to do the "static" trick but with another tag (say media) e.g <img src="{% media 'image.png' "> to avoid absolute paths?
CutePoison
  • 4,679
  • 5
  • 28
  • 63
  • 1
    You have to add MEDIA_ROOT and MEDIA_URL in settings and in urls.py. – Biplove Lamichhane Mar 08 '21 at 12:51
  • 1
    The fact that you need to write the url manually means this is not a users media. Meaning this is a **static** image. Just put it in your static folder then. – Abdul Aziz Barkat Mar 08 '21 at 12:51
  • Biplove, I have added those, and it wont work – CutePoison Mar 08 '21 at 12:54
  • are you trying to show uploaded content or static content? – AMG Mar 08 '21 at 12:56
  • @CutePoison check this question [What is the difference between static files and media files in Django?](https://stackoverflow.com/questions/5016589/what-is-the-difference-between-static-files-and-media-files-in-django) – Abdul Aziz Barkat Mar 08 '21 at 12:57
  • Does this answer your question? [django html template can't find static css and js files](https://stackoverflow.com/questions/66437690/django-html-template-cant-find-static-css-and-js-files) – Ivan Starostin Mar 08 '21 at 13:44

1 Answers1

0

You can create a new folder named img in the static folder, then paste your image in the img folder such that the path to the image will be like this: static -> img -> image.png. You can load the image in HTML like this:

<img src="{% static 'img/image.png'">
  • That is exactly the workaround I'm doing at the moment - the question is, why I just cant place a folder called `media` in root and then use `scr="media/img.png"` – CutePoison Mar 09 '21 at 05:14