Search code examples
pythonhtmldjangoimageweb

Images not appearing on page - Django


I'm writing my django tutorial project and I've run into a problem that hasn't happened before. When I try to display a picture loaded into a model instance using it, it does not want to be displayed in any way, while the rest of the model fields are displayed correctly: models.py:

from django.db import models
from django.urls import reverse



class Product(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(unique=True)
    price = models.PositiveIntegerField()
    description = models.TextField()
    time_create = models.TimeField(auto_now_add=True)
    is_published = models.BooleanField(default=True)
    category = models.ForeignKey('ProductCategory', on_delete=models.PROTECT, verbose_name="Категории")
    brand = models.ForeignKey('Brand', on_delete=models.PROTECT, verbose_name="Бренд")
    photo_front = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Главное фото", blank=True)
    photo2 = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Фото 2", blank=True)
    photo3 = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Фото 3", blank=True)
    photo4 = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Фото 4", blank=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('product', kwargs={'product_slug': self.slug})

test.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
{% for b in posts %}
<p>{{ b.title }}</p>
<img src="{{ b.photo_front.url }}">
{% endfor %}
</body>
</html>

the result is the following output: Images not found

And this is what the code outputs in the browser: Browser code

And this is what the console says Not Found: /media/photos/2023/03/16/616036_XJFF9_1152_001_100_0000_Light-Cotton-T-shirt-with-Gucci-Blade-print.jpg Not Found: /media/photos/2023/03/16/623953_XDBBQ_4011_001_100_0000_Light-Regular-fit-washed-jeans.jpg Not Found: /media/photos/2023/03/16/clipboard_image_bfd7cf0e7879207e.jpg

In general, I assume that the error lies in the wrong path, but I checked as much as I could and tried to fix it, nothing helps. Here is a photo of the folders: Path to folder

settings.py

    DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1', 'localhost']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'store.apps.StoreConfig',
]

STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_DIRS = []

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


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

store/urls.py

from django.urls import path

from .views import *


urlpatterns = [
    path('', index, name='Home'),
    path('product/<slug:product_slug>', product, name='Product'),
    path('cart/', cart, name='Cart'),
    path('contacts/', contacts, name='Contacts'),
    path('listing/', product_list, name='Product_List'),
    path('login/', login, name='Login'),
    path('registration/', register, name='Register'),
    path('checkout/', checkout, name='Checkout'),
    path('invoice/', invoice, name='Invoice'),
    path('orders/', orders, name='Orders'),
    #path('product-single-col/', product_single_col, name='Product_Col'),
    path('about/', about, name='About'),
    path('sitemap/', sitemap, name='Sitemap'),
    path('test/', test, name='test'),


]

librinstore/urls.py

from django.contrib import admin
from django.urls import path, include

from store.views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('store.urls')),
]

I tried to manually insert path to file, moving the file to the same directory where html file was, i tried reinstalling Pillow. Nothing works

Please help, im struggling with this for a week now.


Solution

  • In order to serve uploaded files during development you need to add a new endpoint:

    from django.conf import settings
    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('store.urls')),
    ]
    
    if settings.DEBUG:
        from django.conf.urls.static import static
    
        urlpatterns += static(settings.MEDIA_URL,
                              document_root=settings.MEDIA_ROOT)