无法在Django中显示图片

时间:2019-07-05 07:59:52

标签: django

files of whole project

我已经正确设置了媒体url的路径,但仍然无法在allproducts.html中找到图像,而在category.html中却可以从媒体目录中找到图像。我无法理解此错误的原因。

allproducts.html

{% for sub in subcategory %}
    {% for p in sub.product_set.all  %}

        <div class="product">
            <div><h3 class="logo header_content d-flex flex-row align-items-center justify-content-start">{{sub.name}}</h3></div>
            <div class="product_image"><img src="media/{{p.image}}" alt=""></div>
            <div class="product_content">
                <div class="product_title"><a href="/shop/product/{{p.id}}">{{p.name}}</a></div>
                <div class="product_price">{{p.price}}</div>
            </div>
        </div>

    {% endfor %}
    <div></div>
{% endfor %}

settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATIC_DIR,
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'

urls.py

urlpatterns = [
    path('',views.index, name="index"),
    path('cart',views.cart, name="cart"),
    path('categories',views.categories, name="categories"),
    path('checkout',views.checkout, name="checkout"),
    path('contact',views.contact, name="contact"),
    path('product/<int:pk>/',views.product, name="product"),
    path('allproducts/<int:pk>/', views.allproducts, name="allproduct"),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

def allproducts(request, pk):
    products = Product.objects.all()
    category = Category.objects.get(pk=pk)
    subcategory = Subcategory.objects.filter(category = category)

    return render(request, 'shop/allproducts.html',
                      {'products':products, 'subcategory':subcategory,
                       'category':category})

项目文件

kh
kh
  .idea
  __init__.py
  settings.py
  urls.py
  wsgi.py
media
  shop
  images
    test.jpg
shop
db.sqlite3
manage.py

1 个答案:

答案 0 :(得分:1)

您肯定需要一个斜杠:

<img src="/media/{{p.image}}" alt="">

但是最好让图像本身输出完整路径:

<img src="{{p.image.url}}" alt="">