无法在django中显示数据库中的图像

ryhaxcpt  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(104)

index.html
<img src="{{beat.image.url}}" class="card-img-top" alt="{{beat.name}}">
settings.py

STATIC_URL = '/static/'

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

models.py
image = models.ImageField(upload_to='images', blank=True)
urls.py

urlpatterns = [
    path('', views.index, name='index'),
    path('test', views.test, name='test'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

beat.image.url不工作

cxfofazt

cxfofazt1#

您可能已经在模板中传递了queryset。如果是这样的话,你需要在模板中使用for循环来访问它,如下所示:

{% for content in beat %}
<img src="{{content.image.url}}" class="card-img-top" alt="{{content.name}}">
{% endfor %}

请发布views.py,以便我们进一步解决问题。
首先编辑您的urls.py:

from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
from django.urls import path, re_path

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

相关问题