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

时间:2018-05-22 10:06:16

标签: html django django-models

我想获取产品模型的图像图像模型并显示购物车模板

这是我的代码:

电子商务/ 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()

车/ 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.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>

我已阅读此link

但这对我没用,请帮助我,我是新来的

谢谢

1 个答案:

答案 0 :(得分:1)

您应该使用反向查找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变量传递给模板上下文。