Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display product images from a loop using django

I would like to display my images from a loop, my images are stored on static/images and in the database the image field is a CharField of image name.

settings.py

STATICFILES_DIRS = [
   BASE_DIR / 'static',
]
STATIC_URL = 'static/'
LOGIN_REDIRECT_URL='account:profile'
LOGIN_URL='account:login'

models.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 class Product(models.Model):
    name=models.CharField(max_length=70,blank=True,null=True)
    price=models.IntegerField()
    image=models.CharField(max_length=100,blank=True,null=True)

views.py

{% load static %}
{% for product in products %}
   <div class="card">
     <div class="card-image">
        <img src="{% static 'images/{{product.image}}' %}">     
    </div>
   </div>
{% endfor %}

I can’t display the image. How to do ??

>Solution :

Source should be:

<img src="{{product.image.url}}">  

If product does not have any image, this might throw an error. So, for that you can use:

 {% if product.image %}
 <img src="{{product.image.url}}">  
 {% else %}
  <img src="{% static 'images/product.jpg' %}">  
  {% endif %}

Replace 'images/product.jpg' with a static image of your choice.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading