简体   繁体   中英

I cannot show my image in my django HTML template

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM