【问题标题】:display image from django model to template using for loop使用for循环将图像从django模型显示到模板
【发布时间】:2020-09-21 03:40:46
【问题描述】:

所以我想在表格中显示从产品模型到模板的产品图像,但是我编写的下面的代码在图像上显示损坏的图像标志并且不起作用 这是我的代码

在 models.py 中


class Product(models.Model):

    Name = models.CharField(max_length=700, null=True)
    Price = models.FloatField(null=True)
    Link = models.URLField(max_length=2000, null=True)
    Image = models.ImageField(null=True)

在我看来.py

from django.shortcuts import render, redirect 
from django.http import HttpResponse
from .models import *


def home(request):

    Products = Product.objects.all()


    context = {'products':Products}
    return render(request, 'Cam/main.html', context)

在模板(html 文件)中:

<div class="container ">

    <table class="table table-hover">
      <thead>
        <tr class="row">
          <th class="col-md-1" >Name</th>
          <th class="col " >Picture</th>
          <th class="col-md-1" >Price</th>
        </tr>
      </thead> 
      <tbody>

        {% for product in products %}

        <tr class="row">
          <td class="col-md-1"> {{product.Name}} </td>
          <td class="col-md-1"><img id="IMG" src="{{product.Image.url}}" ></td> 
          <td class="col-md-1"> {{product.Price}} </td>
        </tr>
        {% endfor %}

【问题讨论】:

  • docs.djangoproject.com/en/3.0/howto/static-files,你确定图片上传正确吗?此外,模型字段名称应写成蛇形,不要大写
  • 是的,我认为图片上传正确,上传后它们会自动转换为项目文件,而不是静态/图片文件,这样好吗?
  • 当您检查元素时,您是否看到正确的 URL,文档不仅涉及静态文件,还涉及媒体文件 /#serving-files-uploaded-by-a-user-during-development
  • 当我检查管理页面并检查图像字段时,我看到了正确的网址

标签: python django django-models django-rest-framework django-templates


【解决方案1】:

首先,您没有遵循 Python 约定:类应该大写(Pascal Case),属性应该小写:

class Product(models.Model):
    name = models.CharField(max_length=700, null=True)
    price = models.FloatField(null=True)
    link = models.URLField(max_length=2000, null=True)
    image = models.ImageField(null=True)

要回答这个问题,请确保您已完成以下操作:

urls.py

urlpatterns = [
    # urls/path
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

模板

<img src="{{ product.image.url }}">

型号:

image = models.ImageField(upload_to = 'product-img/', null=True)

如果图像已保存,您会在文件夹 media/product-img 中找到它

【讨论】:

  • 非常感谢,这很有帮助
猜你喜欢
  • 1970-01-01
  • 2017-03-27
  • 2018-08-11
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-10
  • 2021-10-17
相关资源
最近更新 更多