django - 在 django 模板的相关模型中获取 image.url 作为属性
问题描述
我有一个 ListView,我想在其中列出产品。问题是我无法获得这些产品的相关图片,因为它们的型号不同。
产品型号为:
class Product(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, verbose_name='marca')
name = models.CharField('nombre', max_length=40)
description = models.TextField('descripción', blank=True)
price = models.DecimalField(max_digits=8, decimal_places=2)
slug = models.SlugField(max_length=50)
active = models.BooleanField('activo',default=True)
in_stock = models.BooleanField('en stock', default=True)
tags = models.ManyToManyField(ProductTag, blank=True)
date_updated = models.DateTimeField('última actualización', auto_now=True)
图像模型为:
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='producto')
image = models.ImageField('imagen', upload_to="product-images")
thumbnail = models.ImageField('miniatura', upload_to="product-thumbnails", null=True)
context.update
为了在我在视图中使用的模板中获取两个模型。
class ProductListView(ListView):
template_name = 'product_list.html'
context_object_name = 'products_list'
model = models.Product
paginate_by = 4
def get_context_data(self, **kwargs):
context = super(ProductListView, self).get_context_data(**kwargs)
context.update({'product_images_list': models.ProductImage.objects.all()})
return context
def get_queryset(self):
tag = self.kwargs['tag']
self.tag = None
if tag != 'all':
self.tag = get_object_or_404(models.ProductTag, slug=tag)
if self.tag:
products = models.Product.objects.active().filter(tags=self.tag)
else:
products = models.Product.objects.active()
return products.order_by('name')
此外,我创建了一个过滤器来在 forloop 中迭代两个模型,但我认为没有用,因为我不想迭代这两个模型,我只想获取与产品的 FK 匹配的第一个图像以在模板中显示它:
from django import template
register = template.Library()
@register.filter(name='zip')
def zip_lists(a, b):
return zip(a, b)
我使用的模板是:
{% extends 'base.html' %}
{% load humanize %}
{% load product_extras %}
{% block content %}
<div class="destacados">
{% for product, image in products_list|zip:product_images_list %}
<div class="collections coll-watches">
<img class="foto" src="{{ image.thumbnail.url }}">
<p class="prod-description">{{ product.name }}</p>
<p class="prod-description prices"><strong>$ {{ product.price|intcomma }}</strong></p>
<a class="boton-tr boton-tr-watches" href="#">Agregar al carrito</a>
</div>
{% endfor %}
</div>
{% endblock content %}
如您所见,问题出在<img class="foto" src="{{ image.thumbnail.url }}">
. 我知道这是不正确的,但我不知道如何通过其 FK 获取与产品相关的图像。
我是 django 新手(只有两个月),我相信这应该更容易,但我可以弄清楚......
任何帮助,将不胜感激!!此致
解决方案
非常感谢@bmons。我不得不稍微修改一下方法,但你的回答给了我需要的线索。
这是最终代码:
def get_image_url(self):
img = self.productimage_set.first().thumbnail.url
if img:
return img
return img #None
使用时img = self.productimage_set.thumbnail.first()
出现 RelatedManager 错误。无论如何,我真的很感谢你的帮助!!干杯
推荐阅读
- java - 创建排除引号内容的空格分隔列表
- java - 如何根据java 8中的某些条件迭代和过滤列表?
- c - 在变量初始化上强制转换指向 Matrix 的指针是引用或副本
- java - 自定义对象如何存储在 HashMap 中
- javascript - 带有 boostrap-vue b-table 的 V 模型
- ios - MPMediaPickerController 从不显示在 iOS 13 上,没有打印错误
- c - 运行 Windows SendInput API 时显示器闪烁
- arrays - 计算文本评论中大写单词的数量
- c++ - QT5:无法使用 qss 文件设置样式表属性
- reactjs - MobX 将存储重置为初始状态