【问题标题】:Display images in the list in HTML在 HTML 列表中显示图像
【发布时间】:2020-10-07 19:45:52
【问题描述】:

我想以列表的形式显示我的所有药物。我从 mysql 数据库中获取值。但我无法显示图像。

我得到无意义的输出,例如 b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01... 而不是图像。

这是我的代码。我该如何解决?

models.py

class Medicine(models.Model):

    #user = models.TextField(User)

    medicine_name = models.CharField(max_length=100)
    medicine_info = RichTextField(verbose_name="notes")
    medicine_code = models.CharField(max_length=100)
    medicine_price = models.IntegerField()
    medicine_stock = models.IntegerField()
    medicine_image = models.ImageField(null=True, blank=True)

    def get_image(self):
        if self.medicine_image and hasattr(self.img_photo, 'url'):
            return self.medicine_image.url
        else:
            return

    def __str__(self):
        return self.medicine_name

    class Meta:
        ordering = ['medicine_name']

views.py

def list_item(request):
    medicines = Medicine.objects.filter()
    return render(request, 'medicine_list.html', {'medicines': medicines})

medicine_list.html

  <table class='table'>
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Info</th>
            <th>Barcode</th>
            <th>Stock</th>
            <th>Image</th>
          </tr>
        </thead>
      {% for medicine in medicines %}
          <tr>
            <td>{{medicine.id }}</td>
            <td>{{ medicine.medicine_name }}</td>
            <td>{{ medicine.medicine_info }}</td>
            <td>{{ medicine.medicine_code }}</td>
            <td>{{ medicine.medicine_price }}</td>
            <td>{{ medicine.medicine_image }}</td>
          </tr>
      {% endfor %}
    </table>

【问题讨论】:

  • 使用&lt;td&gt;&lt;img src="{{ medicine.medicine_image.url }}"&gt;&lt;/td&gt;
  • 我试了一下,但现在什么都没有显示@pandafy
  • 数据库中medicine_image的值是什么样的?
  • 你为什么不用medicine.get_image

标签: html mysql django


【解决方案1】:

在您的get_image 函数中,您检查self.img_photo 是否具有某个属性,但问题是self.img_photo 不存在,因此else 语句运行并且不返回任何内容。

您的函数应如下所示:

def get_image(self):
        if self.medicine_image and hasattr(self.medicine_image, 'url'):
            return self.medicine_image.url
        else:
            # return whatever you want here

我还建议为您的图像指定 upload_to 值,如下所示:

medicine_image = models.ImageField(upload_to='images', null=True, blank=True)

请注意,“图像”可以是任何你想要的。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2013-03-26
    • 2013-04-24
    相关资源
    最近更新 更多