【问题标题】:How to display multiple images for django model如何为 django 模型显示多个图像
【发布时间】:2018-08-10 06:29:26
【问题描述】:

这是我的图像模型,我绑定到模型产品

class Image(models.Model):
    name = models.CharField(blank=True,max_length=20)
    product = models.ForeignKey(Product)
    image = models.ImageField(blank=True,null=True)

    def __str__(self):
        return self.name

这是我用来尝试显示图像的视图 def 类别(请求,类别 ID): 类别 = Category.objects.all() 图像 = Image.objects.all() 产品 = Product.objects.all() 尝试: 类别 = Category.objects.get(id=category_id) 除了 Category.DoesNotExist: 类别 = 无;

    template = loader.get_template('index.html')
    context = {
        'category': category,
        'categories': categories,
        'images': images,
        'products': products
    }
    return HttpResponse(template.render(context,request))

这里是html

 {% for image in images %}
            <a href="#" class="image"><img src="{{ image.url }}"></a>
 {% endfor %}

我知道这绝对行不通,但至少这段代码显示页面而不是错误,所以我一直在使用它,谁能指出我正确的方向来显示与每个产品关联的每个图像。 谢谢!

【问题讨论】:

  • 您要显示所有产品及其各自的图片
  • 是的,没错。
  • 你是否在 settings.py 中设置了媒体 url 和媒体根目录,像这样 MEDIA_URL = '/uploads/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads/')

标签: html django image django-models web-deployment


【解决方案1】:

你可以试试这个:

  {% for product in products%}
  <p> {{product.name}}  </p>
    {% for simage in product.image_set.all %}
      {% if simage.image%}
        <a href="#" class="image"><img src="{{ simage.image.url }}"></a>
      {% endif %} 
    {% endfor %}
  {% endfor %}

【讨论】:

  • 这是我的第一次尝试,我再次尝试,没有导致任何错误但图像没有显示。
  • 虽然不是 {%for product in products%} 我做 {% for product in category.product_set.all %} 因为我显示的产品与基本功能与图像相同的模型类别相关联型号
  • 试试 {simage.image.url }
  • 我收到错误“'image' 属性没有与之关联的文件”,这是我第一次尝试时的初始错误。
  • 尝试 {% if simage.image% } show Image {%end if%}
猜你喜欢
  • 2018-02-17
  • 1970-01-01
  • 2018-11-16
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 2018-10-22
相关资源
最近更新 更多