djangoimagefield

I'm using Django ImageField but I can't access the images in my web page


this is models.py

from django.db import models

# Create your models here.
class Products(models.Model):
    name_product=models.CharField(max_length=100)
    category_product=models.CharField(max_length=100)
    price_product=models.CharField(max_length=200)
    image_product=models.ImageField(default='Image.png',upload_to='web/')
    description_product=models.CharField(max_length=400)

this is views.py

from django.shortcuts import render
from .models import Products

# Create your views here.

def asli(request):
    data=Products.objects.all()
    return render(request,'home.html',{'data':data})

this is my web page

<img src="{{ data.image_product.url }}" alt="Product Image">

I tried this code in the setting.py but still it doesn't show my photos on my web page P.s: The connection has been established correctly

MEDIA_URL = "media/"
MEDIA_ROOT = BASE_DIR / "media"

Solution

  • 1. You have to ensure that your media files are served on the given MEDIA_URL as Django will not handle that for you. You may use the local Django server since you are still in DEBUG mode.

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [•••Rest of code•••]
    
    if settings.DEBUG:
        urlpatterns += [
            static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
        ]

    2. data is a QuerySet. You have to iterate over it before you can get each value within. See for template tag.

    {% for product in data %}
        <p>{{ product.name_product }} </p>
        <p>{{ product.category_product }} </p>
        <p>{{ product.price_product }} </p>
        <img src="{{ product.image_product.url }}" alt="{{ product.name_product }}" />
        <p>{{ product.description_product }} </p>
    {% endfor %}