yg lin
yg lin

Reputation: 123

how to show picture in the html by django

I can not show the picture in the html by django. There is my project enter image description here

This my project setting

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static/')

urls

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns=[
    path('',views.main_view,name='main_view'),
]
urlpatterns += staticfiles_urlpatterns()

main.html

<img src="{% static '/my/1.jpg' %}" alt="My image">

There is my result.As you can see,the picture is desapper

setting.py

MEDIA_URL = '/pic/'
MEDIA_ROOT = os.path.join(BASE_DIR,'pic/')

urls.py

urlpatterns+=static('/pic/', document_root=settings.MEDIA_ROOT)

main.html

<img src="pic/1.jpg" alt="My image">

enter image description here

Upvotes: 0

Views: 79

Answers (1)

user8060120
user8060120

Reputation:

you just should to remove slash, because, in the settings STATIC_URL already has it.

<img src="{% static 'my/1.jpg' %}" alt="My image">
               <!-- ^^^ -->

and by docs check DEBUG settings

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns += staticfiles_urlpatterns()

This helper function will only work if DEBUG is True

and try to use standard static instead of staticfiles_urlpatterns

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Upvotes: 1

Related Questions