1

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

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
Gin
  • 11
  • 3
  • Please edit your question and replace link/screenshot of your code with the code itself. https://stackoverflow.com/help/how-to-ask – Ivan Starostin Mar 27 '21 at 18:16
  • Interesting. Please take a look at the answer for this question: https://stackoverflow.com/questions/66833381/static-media-images-are-not-displaying-in-django/66834540#66834540 – Ivan Starostin Mar 27 '21 at 18:23
  • Same for your case: these are not **static** files, but **media** files. – Ivan Starostin Mar 27 '21 at 18:24

1 Answers1

1

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 {}

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39