I cannot show my image in my django HTML template

30 Views Asked by At

I have this model:

class MyModel(Model):

    other_field = CharField(max_length=200)
    image = ImageField(upload_to='images/', null=True, blank=True, )

I have this in my project settings file:

MEDIA_URL = '/media/'  # new
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')  # new

I also have an "images" folder in my media folder. These are the address of some of the files. To ensure you everything is ok:

-myproject>myproject>settings.py

-myproject>media>images>myimage1.png

-myproject>media>images>myimage2.png

I enter into the shell

Python manage.py shell

Then:

from myapp.models import MyModel
model_ins = MyModel.objects.get(id=1)
model_ins.image.url

It returns :

'/media/images/myimage1.png'

I have this HTML Template (simplified):

{% load static %}<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
    <img src="{{ mymodel_ins.image.url }}">
</body>
</html>

it shows me no image. What is the reason?

1

There are 1 best solutions below

0
On

I found the answer

This should be added to the main url file of the project:

if settings.DEBUG:  # new
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

However, I still do not understand the logic and what it means