如何在 div 的 html 背景 url 中使用产品图片?姜戈

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

我不知道如何在我的模板中显示产品图片。 图像需要进入 div 的背景 - url,使用静态不是一个选项,因为它不会来自模型。

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 %}
   ....

型号

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

查看

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

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

设置

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

如果你知道怎么做,请给我一个答案?查看图片了解更多信息

存储在 ImageField 中的文件是 media 文件,而不是 static

它们由 MEDIA_ROOTMEDIA_URL 设置管理,并且必须在这样的模板中引用:

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

注意 {}

周围的附加单引号