how to display image to template from imagefield in django

Submitted 3 years, 6 months ago
Ticket #198
Views 1017
Language/Framework Django
Priority Medium
Status Closed

My template cannot display the image coming from my model.

src attribute comes with proper field but it does not display the proper image

template:

       <div class="grid-product">
  
    {% for p in prod %}
    
    
    <div class="  product-grid">
        <div class="content_box"><a href="single.html">
        <div class="left-grid-view grid-view-left">
             <img  class="img-responsive watch-right" alt="not found" src="{{p.photo}}"/>
                <div class="mask">
                    <div class="info">Quick View</div>
                </div>
              </a>
        </div>
            <h4><a href="#"></a></h4>
             <p>It is a long established fact that a reader{{ p.p_name }}</p>
             Rs. 499
        </div>
   </div>
    {% endfor %} 
         <div id="show"></div>
    <div class="clearfix"> </div>
</div>

model:

class product(models.Model):
    p_id=models.AutoField(primary_key=True)
    ps_id=models.ForeignKey(alphasubcat,on_delete=models.CASCADE)
    p_name=models.CharField(max_length=100,null=True,blank=True)
    photo = models.ImageField(upload_to='productimage',blank=True)
    price=models.IntegerField()
    def __str__(self):
        return self.p_name

view:

def produc(request):
    param=dict()
    cat=categories.objects.all()
    sub=subcategories.objects.all()
    temp=request.GET['p']
    prod=product.objects.filter(ps_id=alphasubcat.objects.get(as_name=temp))
    param['prod']=prod
    param['cat']=cat
    param['sub']=sub
    return render(request,"product.html",param)
Submitted on Oct 04, 20
add a comment

1 Answer

Verified

you can access image url by {{p.photo.url}}. but as here in your model:

photo = models.ImageField(upload_to='productimage, blank=True)

(blank=True) you would want to use something like:

<img  class="img-responsive watch-right" alt="not found" src={% if p.photo %}"{{p.photo.url}

Submitted 3 years, 6 months ago


Latest Blogs