Answer the question
In order to leave comments, you need to log in
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'),)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('webapp.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{% if item.PM_image %}
<img style="width:100px; height: 100px" scr="{{ item.PM_image.url }}" />
{{ item.PM_image }}
{% endif %}
<td>
<img style="width:100px; height: 100px" scr="/media/printermodel/M2040dn.png">
printermodel/M2040dn.png
</td>
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
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,}),]
from django.views.static import serve
from django.urls import re_path
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)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question