Jigar Tarpara
Jigar Tarpara

Reputation: 59

how to display image to template from imagefield in django

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)

Upvotes: 4

Views: 6386

Answers (4)

Jigar Tarpara
Jigar Tarpara

Reputation: 59

this is work for my problem here static is my root folder for media file

img  class="img-responsive watch-right" alt="not found" src="static/{{p.photo}}"

Upvotes: 0

varnothing
varnothing

Reputation: 1299

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}}"{% else %}"/something/else.png"{% endif %}/>

Upvotes: 6

SuReSh
SuReSh

Reputation: 1511

On your local server

<img  class="img-responsive watch-right" alt="not found" src="127.0.0.1:8000/{{p.photo.url}}"/>

thats fine settings in settings.py

STATIC_URL = '/static/' 

STATICFILES_DIRS=[ os.path.join(BASE_DIR,"static"), ] 

STATIC_ROOT=os.path.join(os.path.dirname(BASE_DIR),"static_cdn") 

MEDIA_ROOT=os.path.join(os.path.dirname(BASE_DIR),"src/media")

MEDIA_URL="/img/" –

but also debug that STATIC_ROOT is return domain/link-to-image

Upvotes: 0

ilse2005
ilse2005

Reputation: 11429

Try changing your code to

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

Upvotes: 1

Related Questions