Please help. Images do not appear

Hi, I am following a tutorial from Code with Stein- Learn Django by building an Online Marketplace. I have gotten up to 0:42:44 on the video tut. Somehow my images do not load.
I have tried to find what is missing or what shouldn’t be there. Please help. I notice on line 14 in the index.html file that if I follow the tutorial and type

<img src="{{item.image.url}}" class="rounded-t-xl">

I get an error. The page does not load. However when I type

<img src="{{item.images.url}}" class="rounded-t-xl">

the page loads alright.
Here is my index.html file

  {% extends "core/base.html" %}Puddle

{% block title %}Welcome{% endblock title %}

{% block content %}
<div class="mt-6 px-6 py-12 bg-gray-100 rounded-xl">
    <h2 class="mb-12 text-2xl text-center">Newest Items</h2>

    <div class="grid grid-cols-3 gap-3">
        {% for item in items  %}
        <div>
            <a href="#">
                <div>
                <img src="{{item.images.url}}" class="rounded-t-xl">
                </div>
                <div class="p-6 bg-white rounded-b-xl">
                    <h2 class="text-2xl">{{item.name}}</h2>
                    <p class="text-gray-500">Price:{{ item.price}} </p>
                </div>

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

</div>
{% endblock content %}

the models.py file

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=255)

    class Meta:
        ordering = ('name',)
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.name
    
class Item(models.Model):
    category = models.ForeignKey(Category, related_name='items', on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    price = models.FloatField()
    image = models.ImageField(upload_to='item_images', blank=True, null=True)
    is_sold = models.BooleanField(default=False)
    created_by = models.ForeignKey(User, related_name='items', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

and the views.py file

from django.shortcuts import render

from item.models import Category,Item

def index(request):
    items = Item.objects.filter(is_sold=False)[0:6]
    categories = Category.objects.all()

    return render(request, 'core/index.html', {
        'categories': categories, 
        'items': items,
    })

def contact(request):
    return render(request, 'core/contact.html')

Please specify what the error is that you are receiving.

But you’re not seeing any images, right? This is because there is no “images” attribute in Item.

Okay. So how do I put an images attribute in Item?

You have an image attribute already. The name of the variable in Item is image, not images.

That is where I have the challenge. When I type image(like is there in Item) I get an error message. However when I type images I see the page load but no images appear

We need to address the error.

As I asked before:

Yes, That is why I am sort of flummoxed. Give me one moment let me go back to the code

Okay. I went back to my code and typed in the image attribute. This is the error I now get.


ValueError at /

The 'image' attribute has no file associated with it.

Request Method: 	GET
Request URL: 	http://127.0.0.1:8000/
Django Version: 	5.1.1
Exception Type: 	ValueError
Exception Value: 	

The 'image' attribute has no file associated with it.

Exception Location: 	C:\Users\hp\Documents\Learn Python\Django\Code with Stein\Puddle\venstein\Lib\site-packages\django\db\models\fields\files.py, line 44, in _require_file
Raised during: 	core.views.index
Python Executable: 	C:\Users\hp\Documents\Learn Python\Django\Code with Stein\Puddle\venstein\Scripts\python.exe
Python Version: 	3.12.5
Python Path: 	

['C:\\Users\\hp\\Documents\\Learn Python\\Django\\Code with '
 'Stein\\Puddle\\puddle',
 'C:\\Program '
 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.12_3.12.1520.0_x64__qbz5n2kfra8p0\\python312.zip',
 'C:\\Program '
 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.12_3.12.1520.0_x64__qbz5n2kfra8p0\\DLLs',
 'C:\\Program '
 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.12_3.12.1520.0_x64__qbz5n2kfra8p0\\Lib',
 'C:\\Program '
 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.12_3.12.1520.0_x64__qbz5n2kfra8p0',
 'C:\\Users\\hp\\Documents\\Learn Python\\Django\\Code with '
 'Stein\\Puddle\\venstein',
 'C:\\Users\\hp\\Documents\\Learn Python\\Django\\Code with '
 'Stein\\Puddle\\venstein\\Lib\\site-packages']

Server time: 	Fri, 06 Sep 2024 20:49:54 +0000
Error during template rendering

In template C:\Users\hp\Documents\Learn Python\Django\Code with Stein\Puddle\puddle\core\templates\core\index.html, error at line 14
The 'image' attribute has no file associated with it.
4 	
5 	{% block content %}
6 	<div class="mt-6 px-6 py-12 bg-gray-100 rounded-xl">
7 	    <h2 class="mb-12 text-2xl text-center">Newest Items</h2>
8 	
9 	    <div class="grid grid-cols-3 gap-3">
10 	        {% for item in items  %}
11 	        <div>
12 	            <a href="#">
13 	                <div>
14 	                <img src="{{item.image.url}}" class="rounded-t-xl">
15 	                </div>
16 	                <div class="p-6 bg-white rounded-b-xl">
17 	                    <h2 class="text-2xl">{{item.name}}</h2>
18 	                    <p class="text-gray-500">Price:{{ item.price}} </p>
19 	                </div>
20 	
21 	            </a>
22 	            
23 	        </div>
24 	        {% endfor %}

The error is highlighted in red on line 14 in my editor

That’s exactly the issue.

You have an Item, but that item doesn’t have an image.

You need to either upload an image for that Item, or you need to change your template so that it doesn’t try to render item.image.url if there’s no image. (Perhaps put it inside an {% if %} tag. There are other options as well.)

Thank you for your patience. Let me go over the code again.

To be clear - this is not a problem with your code.

Fundamentally, this error is the result of a problem with your data. (That, and the fact that your template can’t handle the data problem.)

Thanks. I went to my admin dashboard and it seems what I uploaded is a webpage. the extension is showing .webp. Let me try and use another image and see if that works

Note: You will want to make sure that all instances of Item have images uploaded for them.

Okay. I am trying to upload new images. I deleted the ones that were there befoe

Ken thank you very much. I now see the images. I uploaded new images with the .jpeg rather than the .webp extension. Thank you.

One of my images is very large. Is there any way I can reduce its size. I used to know how to do so with ordinary html. How can I do so with Django?

Just like in regular HTML you can set the size that the image is going to be displayed. However, this doesn’t reduce the size of the image, it just reduces the size that is being displayed. (The server is still sending the entire file, and the browser still needs to handle it. It just shrinks what’s being seen.)