Gin
Gin

Reputation: 21

How do I use product image in html background url of a div?. Django

I don't know how I can display a product-image inside my template. The image needs to go inside a background-url of a div, using static isn't a option, cause then its not coming form models.

Html

 ....
    {% if products %}
      {% for product in products %}
    
       <div class="product-grid" style="background-image:url({% static 'images/product-1.jpg' %});">
         <div class="inner">
            <p>
               <a href="{% url 'single_product' %}" class="icon"><i class="icon-shopping-cart"></i></a>
               <a href="{% url 'single_product' %}" class="icon"><i class="icon-eye"></i></a>
           </p>
         </div>
      </div>
        {{ product.title }}
        ${{ product.price }}
      {% endfor %}
    {% endif %}
   ....

Models

class Product(models.Model):
    ....
    photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/')
    def __str__(self):
        return self.title

View

def shop(request):
    products = Product.objects.order_by('-upload_date').filter(is_published=True)

    context = {'products': products}
    return render(request, 'shop/shop.html', context)

Settings

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'ecom/static')
]

Please give me a answer if you know how to do this? see image for more info

Upvotes: 2

Views: 999

Answers (1)

IVNSTN
IVNSTN

Reputation: 9299

Files stored in ImageField are media files, not static.

They are managed by MEDIA_ROOT and MEDIA_URL settings and must be referenced in templates like that:

style="background-image:url('{% product.photo_main.url %}');"

note additional single quotes around {}

Upvotes: 2

Related Questions