alcoder
alcoder

Reputation: 457

Can't display images django

How can I display images from django models on tis page datat.ru/shop ?

I the source page code see <img class='img-fluid w-100' src="/media/images/2.png" alt="img" />

But only http://datat.ru/static/media/images/2.png returns image How can I convert src="{{ shop.cover.url }}" to 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 %}

Upvotes: 1

Views: 68

Answers (1)

Jay
Jay

Reputation: 1319

add this to settings.py

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

and this to urls

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

Upvotes: 1

Related Questions