Image in web browser not getting rendered, showing alt attribute's message, I am using Django's lightweight server not only that but the image is not visible even in simple static html file but it is getting rendered when it's address in pasted in browser's search bar.
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{% for prod in allProds %}
{{prod.name}}<br>
<img src="/media/{{prod.img}}"><br>
{{prod.img}}
{{prod.smdesc}}<br>
{{prod.bgdesc}} <br>
{% endfor %}
</body>
</html>
from django.db import models
import uuid
from django.contrib.auth.models import User
class Category(models.Model):
category = models.CharField(max_length=50)
class SubCategory(models.Model):
sub_category = models.CharField(max_length=50)
class Product(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=40)
img = models.ImageField(upload_to='shop/images')
smdesc = models.CharField(max_length=100)
bgdesc = models.CharField(max_length=400)
price = models.IntegerField()
in_Stock = models.IntegerField(default=0)
discount = models.IntegerField(default=0)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
date_added = models.DateField(auto_now=True)
def __str__(self):
return f"{self.name} of {self.price}"
class Cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
cart_items = models.ManyToManyField(Product, blank=True, related_name="cart_items")
from django.shortcuts import render
from .models import Product
# Create your views here.
def index(request):
allProds = Product.objects.all()
context = {
'allProds':allProds
}
return render(request, 'ecom/index.html',context)
Please Notify if anyother error is there (the code goes perfect except image) or any best practice
Your image tag should look like this:
<img src="/media/{{prod.img.url}}"><br>
Or if you already referenced /media path in settings.py and url, it should even look something like this:
<img src="{{prod.img.url}}"><br>
For example, if the media folder is in the same directory where the manage.py file is (usually that's the case), in settings.py you add this:
MEDIA_URL="/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
And in your urls.py something like this:
from django.urls import path,include
from django.conf.urls.static import static
from django.conf import settings
path('', include('your_app.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)