如何在django中获得另一个模型的图像?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (105)

我想为我的产品型号获取图像形式的图像模型并显示它的购物车模板。

这是我的代码:

ecommerce/ models.py:

class Product(models.Model):
    name = models.CharField(max_length=200)
    content = models.TextField()
    excerpt = models.TextField()
    price = models.DecimalField(max_digits=6, decimal_places=2)
    status = models.IntegerField(default=0)
    date = models.DateTimeField(auto_now_add=True)
    quantity = models.PositiveIntegerField()
    author = models.PositiveIntegerField()
    featured_image = models.CharField(max_length=300)
    available = models.BooleanField(default=True)

    def __str__(self):
        return self.name

class Image(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image = models.ImageField()

cart/ views.py:

@require_POST
def cart_add(request, product_id):
    cart = Cart(request)
    product = get_object_or_404(Product, pk=product_id)
    form = CartAddProductForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        cart.add(product=product,
                 quantity=cd['quantity'],
                 update_quantity=cd['update'])
    return redirect('cart:cart_detail')    

def cart_detail(request):
    cart = Cart(request)
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'],
                                                                   'update': True})
    return render(request, 'cart_detail.html', {'cart': cart})

cart/templates/ cart.html:

<tbody>
        {% for item in cart %}
            {% with product=item.product %}
            <tr>
                <td>
                    {% for product in products %} 
                        <img src="{{ product.first_image.src }}" alt="" width="auto" height="340"/>
                    {% endfor %}
                </td>
                <td>{{ product.name }}</td>
                .
                .
                .
            </tr>
            {% endwith %}
        {% endfor %}
    </tbody>
提问于
用户回答回答于

你应该使用image_set反向查找。

product.image_set.first.image.url

<img src="{{ product.image_set.first.image.url }}" alt="" width="auto" height="340"/>

让所有图像迭代image_set

{% for image in product.image_set.all %} 
    <img src="{{ image.src }}" alt="" width="auto" height="340"/>
{% endfor %}

请注意,你应删除此部分:

{% for product in products %} 
{% endfor %}

因为你没有将products变量传递给模板上下文。

扫码关注云+社区

领取腾讯云代金券