无法显示图像django

时间:2019-08-24 23:46:50

标签: django python-3.x

如何在tis页面datat.ru/shop上显示django模型的图像?

我的源页面代码请参见<img class='img-fluid w-100' src="/media/images/2.png" alt="img" />

但是只有http://datat.ru/static/media/images/2.png返回图片 如何将 src =“ {{shop.cover.url}}” 转换为 static / media / images / ???

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

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('shop/', views.shop_list, name='shop'),
    path('post/<int:pk>/', views.post_detail, name='post_detail'),

]

models.py

from django.conf import settings
from django.db import models
from django.utils import timezone


class Company(models.Model):
    title = models.TextField()
    cover = models.ImageField(upload_to='images/')

    def __str__(self):
        return self.title

shop_list.html

{% extends 'blog/base.html' %}
{% load staticfiles%}

{% block content %}

    {% for shop in shops %}
        <div class="container">
             <div class="row">
                <img class='img-fluid w-100' src="{{ shop.cover.url }}" alt="img" />
            </div>
        </div>
    {% endfor %}
        <!-- <img class="scale-with-grid" src="{{ shop.cover.url }}"/> -->

{% endblock %}

1 个答案:

答案 0 :(得分:1)

将此添加到settings.py

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

这是网址

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)