首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在django中从另一个模型获取图像

如何在django中从另一个模型获取图像
EN

Stack Overflow用户
提问于 2018-05-22 18:06:16
回答 1查看 286关注 0票数 1

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

这是我的代码:

ecommerce/models.py

代码语言:javascript
复制
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

代码语言:javascript
复制
@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

代码语言:javascript
复制
<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

3.这对我没用,请帮帮我,我对此还不熟悉

谢谢

EN

回答 1

Stack Overflow用户

发布于 2018-05-22 18:14:09

您应该使用反向查找image_set。要获取第一个图像,请执行product.image_set.first.image.url

代码语言:javascript
复制
<img src="{{ product.image_set.first.image.url }}" alt="" width="auto" height="340"/>

要在image_set上迭代所有图像,请执行以下操作

代码语言:javascript
复制
{% for image in product.image_set.all %} 
    <img src="{{ image.src }}" alt="" width="auto" height="340"/>
{% endfor %}

注意:您应该删除此部件:

代码语言:javascript
复制
{% for product in products %} 
{% endfor %}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50464982

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档