N
N
Nposk2021-06-22 08:27:11
Django
Nposk, 2021-06-22 08:27:11

How to display an image in a Django template?

I searched all over the Internet, I can not understand why the pictures in the Django template are not displayed.
The strangest thing is that according to the log, the page does not even seem to request a picture from the server.
settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'files', 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'files', 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),)

urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('webapp.urls')),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Sample
{% if item.PM_image %}
    <img style="width:100px; height: 100px" scr="{{ item.PM_image.url }}" />
    {{ item.PM_image }}
{% endif %}

Page code in the browser
<td>
<img style="width:100px; height: 100px" scr="/media/printermodel/M2040dn.png">
printermodel/M2040dn.png                             
</td>

Server logs
web_1  | [22/Jun/2021 05:15:03] "GET /pm/ HTTP/1.1" 200 7506
web_1  | [22/Jun/2021 05:15:03] "GET /static/css/simple-sidebar.css HTTP/1.1" 200 963
web_1  | [22/Jun/2021 05:15:03] "GET /static/vendor/jquery/jquery.min.js HTTP/1.1" 200 89476
web_1  | [22/Jun/2021 05:15:03] "GET /static/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 200 84152
web_1  | [22/Jun/2021 05:15:03] "GET /static/vendor/bootstrap/css/bootstrap.min.css HTTP/1.1" 200 160392
web_1  | [22/Jun/2021 05:15:03] "GET /static/vendor/jquery/jquery.js HTTP/1.1" 200 287630
web_1  | [22/Jun/2021 05:15:04] "GET /static/vendor/bootstrap/css/bootstrap.min.css.map HTTP/1.1" 200 646986
web_1  | [22/Jun/2021 05:15:04] "GET /static/vendor/bootstrap/js/bootstrap.bundle.min.js.map HTTP/1.1" 200 315680

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
daho005, 2021-06-22
@daho005

Try to write in urls.py at the end:

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += [re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT,}),]

Before importing:
from django.views.static import serve
from django.urls import re_path

D
Daler Hojimatov, 2021-06-24
@EtherDaler

in the main urls after the patterns, write

urlpatterns[...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And then if you have Debug = True, then comment out Static_Root and leave Static_files_dirs. And vice versa, if Debug = False, then leave Static_root, and comment out Static_files_dirs

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question