Image not showing on html page

Hi again! Ive continued working on my website and ive ran into another problem. Ive tweaked my models.py and views so as to allow the admin to insert images, and it works great however, when i go to the html page it shows the broken image icon. The image I added was called Escape_From_Tarkov_Receipt (its the first one i saw! dont make fun of me)

Here’s my code:

views.py

from django.shortcuts import render
from .models import ClothingItem,Categorie,SubCategorie

# Create your views here.

def home(request):
    return render(request,'item_type/home.html',{})

def show_category(request, category_id):
    category = Categorie.objects.get(id=category_id)
    sub_category = SubCategorie.objects.all()
    context = {'category':category,'sub_category':sub_category}
    return render(request, 'item_type/show_category.html',context)

def show_subcategory(request, subcategory_id):
    sub_category = SubCategorie.objects.get(id=subcategory_id)
    item_list = ClothingItem.objects.filter(sub_category=sub_category)
    context = {'sub_category':sub_category,'item_list':item_list}
    return render(request, 'item_type/show_subcategory.html',context)

def show_item(request, item_id):
    item = ClothingItem.objects.get(id=item_id)
    context = {'item':item}
    return render(request, 'item_type/show_item.html',context)

def all_items(request):
    items_list = ClothingItem.objects.all()
    return render(request, 'item_type/clothing_list.html',{'items_list':items_list})

def category(request):
    sub_category = SubCategorie.objects.all()
    category_list = Categorie.objects.all()
    return render(request, 'item_type/categories.html',{'category_list':category_list,'sub_category':sub_category})

def search_item(request):
    if request.method == "POST":
        searched = request.POST['searched']
        items = ClothingItem.objects.filter(name__contains=searched)
        return render(request, 'item_type/search_item.html',{'searched':searched,'items':items})
    else:
        return render(request, 'item_type/search_item.html',{})

models.py

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

# Create your models here.
class ClothingItem(models.Model):
    category = models.ForeignKey('Categorie',null=True,on_delete=models.CASCADE)
    sub_category = models.ForeignKey('SubCategorie',null=True,on_delete=models.CASCADE)
    name = models.CharField( max_length=50)
    brand = models.ForeignKey('Brand',null=True,on_delete=models.CASCADE)
    description = models.TextField(max_length=1000,blank=True)
    item_image = models.ImageField(null=True,blank=True, upload_to="images/")

    def __str__(self):
            return self.name
 

class Categorie(models.Model):
    category = models.CharField(max_length=100)
    def __str__(self):
        return self.category
        
class SubCategorie(models.Model):
    sub_category = models.CharField('Clothing Type',max_length=100)
    def __str__(self):
        return self.sub_category
    
    

class Brand(models.Model):
        brand_name = models.CharField(max_length=100)
 
        class Meta:
            ordering = ['brand_name']
 
        def get_absolute_url(self):
            return reverse("brand_detail", kwargs={"pk": self.pk})
 
        def __str__(self):
            return self.brand_name

urls.py (app wide file)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home,name="home"),
    path('items',views.all_items,name="list_items"),
    path('categories',views.category,name="categories"),
    path('show_category/<category_id>', views.show_category,name="show_category"),
    path('show_subcategory/<subcategory_id>', views.show_subcategory,name="show_subcategory"),
    path('search_item>', views.search_item,name="search_item"),
    path('show_item/<clothingitem_id>', views.show_item,name="show_item"),
]

show_category.html

{% extends 'item_type/base.html' %}

{% block content %}
    <h1>{{category}}</h1><br/>
    {% for i in sub_category %}
        <a href="{% url 'show_subcategory' i.id %}"> {{i}}</a>
    {% endfor %}
{% endblock  %}

show_subcategory.html

{% extends 'item_type/base.html' %}

{% block content %}
    <h1>{{sub_category}}</h1>
    <ul>
    {% for item in item_list %}
        {% if item.item_image %}
            <li>{{item}}</li>
            <br/>
            <img src="{{item.item_image}}">
        {% endif %}
            <li>{{item}}</li>
    {% endfor %}
    </ul>
    
{% endblock  %}

setting.py

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-y5w3h_607ly82zs2b&q)mxq&y3y0dpxjqnurf6o62^y$sqk-ff'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'item_type'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'notte_e_mattina.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'notte_e_mattina.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'
MEDIA_URL = '/media/'

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

STATICFILES_DIRS = (
    os.path.join(BASE_DIR,'static'),
    )

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

urls.py (project wide file)

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('item_type.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

here is a photo of the show_subcategory page

Here is the photo of my terminal which shows Not Found:
Not Found: /show_subcategory/images/Escape_From_Tarkov_Receipt.png
[08/Jan/2023 22:47:47] “GET /show_subcategory/images/Escape_From_Tarkov_Receipt.png HTTP/1.1” 404 3674

As always, thanks in advanced!

It didnt let me attach another media file so here is the image of the terminal:

I think you miss url
USE this
<img src="{{item.item_image.url}}">

instead of this
<img src="{{item.item_image}}">

hope it helps.

2 Likes