Почему картинки не отображаются в django?

enter image description here

Почему не отображаются картинки, загруженные через панель администратора в Django? это код файла views.py

class IndexView(generic.ListView):
template_name = 'Homepage/index.html'
model = Goods
context_object_name = 'goods'

def get_queryset(self):
    """
    Return the last five published questions (not including those set to be
    published in the future).
    """
    return Goods.objects.filter(
        pub_date__lte=timezone.now()
    ).order_by('-pub_date')[:1]

def description(self):
    return self.description_text

def price(self):
    return self.price_text

def image(self):
    return self.image_sale

это код models.py

class Goods(models.Model):
description_text = models.CharField(max_length=200)
price_text = models.CharField(max_length=200)
image_sale = models.ImageField(blank=True, upload_to='media/')
pub_date = models.DateTimeField('date published', null=True)

def __str__(self):
    return self.image_sale

это код settings.py

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

И эта конструкция

enter image description here

это код приложения urls.py

from django.urls import path
from . import views

app_name = 'Homepage'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

это код файла index.html

{% if good.image %}
    <img src="{{ MEDIA_URL }}{{ good.image_sale }}">
    {% endif %}

вы можете просто сделать в своем шаблоне

{% if good.image %}
    <img src="{{good.image_sale.url }}">
    {% endif %}

пожалуйста, вы можете сначала изменить queryset, чтобы проверить, представлено ли изображение

    def get_queryset(self):
    
    """
    Return the last five published questions (not including those set to be
    published in the future).
    """
    good = Goods.objects.filter(
        pub_date__lte=timezone.now()
    ).order_by('-pub_date').first()
    if good.image:
       print(" image url",good.image.url)   
    else:
       print("no image attached")
    return good

Проблема заключалась в том, что я неправильно вводил фотографии в html Это код models.py

class Goods(models.Model):
description_text = models.CharField(max_length=200)
price_text = models.CharField(max_length=200)
image_sale = models.ImageField(blank=True, upload_to='images/')
pub_date = models.DateTimeField('date published', null=True)



def __str__(self):
    return self.description_text

def __str__(self):
    return self.price_text

это код файла views.py

class HomeView(ListView):
model = Goods
template_name = 'index.html'

class IndexView(generic.ListView):
template_name = 'Homepage/index.html'
model = Goods
context_object_name = 'goods'

def get_queryset(self):
    """
    Return the last five published questions (not including those set to be
    published in the future).
    """
    good = Goods.objects.filter(
        pub_date__lte=timezone.now()
    ).order_by('-pub_date')[:1]
    return good

def description(self):
    return self.description_text

def price(self):
    return self.price_text

это код приложения urls.py

from django.urls import path
from django.conf.urls import include, url
from . import views

app_name = 'Homepage'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
    path('', views.HomeView.as_view(), name='home'),

]

это код urls.py

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('grappelli/', include('grappelli.urls')),  # grappelli URLS
    path('', include('Homepage.urls')),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

это html-код

{% for good in goods %}
<img src="{{good.image_sale.url }}">
{% endfor %}

А это строительство сайта enter image description here

Особая благодарность @em0ji. Это парень из русского сообщества Stack Overflow, который решил мою проблему, за что ему огромное спасибо.

Вернуться на верх