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

Displaying uploaded images in the template - Django

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

我有一个页面要 。主模板是蔬菜列表,稍后会有缩略图。

现在,在查看蔬菜的详细信息页面时,我想显示其图片,但模板只显示字符串 'VegetableImage Object' 而不是图片,即使带有 img 标签。

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

models.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',)

主模板视图(所有蔬菜的列表)和详细视图

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="...">

这是从图像域对象访问 url 的方式。

更多技术细节,ImageField inherits from FileField. As it is 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 您需要更改 urls。

您正在尝试输出模型本身,而不是模型上的 image 字段。

您可能想在 for 循环中使用不同的变量名称,否则稍后可能会在尝试找出 "vegetable" 所指的内容时感到困惑。

尝试

{% if view %}
    <h1>Title: {{ vegetable.title }}</h1>
    <h2>Category: {{ vegetable.category }}</h2>
    <p>Thumbnail: {{ vegetable.thumbnail }}</p>
    <p>Images:     
{% for vegetable_image in vegetable.images.all %}
    {{ vegetable_image.image.url }}
    {% endfor %}
</p>


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