gpt4 book ai didi

django - 在模板中显示上传的图像 - Django

转载 作者:行者123 更新时间:2023-12-03 20:18:56 25 4
gpt4 key购买 nike

我正在尝试将上传的图像显示到我想象的蔬菜目录的模板中。

我有一个页面到 add a new vegetable and upload images .主模板是蔬菜列表,稍后会有缩略图。

现在,在查看蔬菜的详细信息页面时,我想显示其图像,但模板仅显示字符串“VegetableImage Object”代替图像,即使带有 img 标签。

我很困惑,因为模板显然已经找到了图像,但它们仅作为通用字符串显示。

模型.py

class Vegetable(models.Model):
title = models.CharField(max_length=0)
category = models.CharField(max_length=50,
choices=CATEGORY_CHOICES)
thumbnail = models.ImageField(upload_to = 'uploaded_images/')


class VegetableImage(models.Model):
vegetable = models.ForeignKey(Vegetable, default=None, related_name='images')
image = models.ImageField(upload_to='images/vegetable',
verbose_name='image',)

主模板 View (所有蔬菜的列表)和详细 View
class VegetableView(generic.ListView):
template_name = 'vegetable/vegetable.html'
context_object_name = 'vegetable_list'

def get_queryset(self):
return Vegetable.objects.all()

class DetailView(generic.DetailView):
model = Vegetable
template_name = 'vegetable/detail.html'

显示蔬菜细节的细节模板
{% if view %}
<h1>Title: {{ vegetable.title }}</h1>
<h2>Category: {{ vegetable.category }}</h2>
<p>Thumbnail: {{ vegetable.thumbnail }}</p>
<p>Images:
{% for vegetable in vegetable.images.all %}
{{ vegetable }}
{% endfor %}
</p>


{% else %}
<p> no vegetables found - error </p>
{% endif %}

最佳答案

尝试在模板中使用以下代码显示图像:

<img src="{{ vegetable.image.url }}" alt="...">

这是您从 imagefield 对象访问 url 的方式。

更多技术细节, ImageField 继承自 FileField .照原样 stated在文档中:

When you access a FileField on a model, you are given an instance of FieldFile as a proxy for accessing the underlying file...



所以:

FieldFile.url

A read-only property to access the file’s relative URL by calling the url() method of the underlying Storage class.



display uploaded user files in development您需要更改网址。

关于django - 在模板中显示上传的图像 - Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32947795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com