1

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

在模型.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)

在我的views.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 %}

4

1 回答 1

0

首先,您没有遵循 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)

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

网址.py

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

设置.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 中找到它

于 2020-06-03T20:16:59.643 回答