Display product images from a loop using django
Question:
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
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 ??
Answers:
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.
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
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 ??
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.