在模板中显示上传的图像 - Django [英] Displaying uploaded images in the template - Django

查看:18
本文介绍了在模板中显示上传的图像 - Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有一个页面可以 继承自 FileField.正如文档中所述:

<块引用>

当您访问模型上的 FileField 时,您将获得一个 FieldFile 实例作为访问底层文件的代理...

因此:

<块引用>

FieldFile.url

通过调用底层 Storage 类的 url() 方法访问文件的相对 URL 的只读属性.

在开发中显示上传的用户文件 您需要更改网址.

I am trying to display uploaded images to a template for my imaginary vegetable catalogue.

I have a page to add a new vegetable and upload images. The main template is a list of vegetables which will later have thumbnails.

Now, when viewing the detail page of the vegetable I want to display its images, but the template is only displaying the string 'VegetableImage Object' in place of an image, even with img tags.

I am confused because the template has obviously found the images but they are displayed just as a generic string.

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

view for main template (a list of all vegetables) and detail 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'

Detail template for displaying detail of vegetable

{% 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 %}

解决方案

Try to display the image using the following code in your template:

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

This is how you access the url from the imagefield object.

In more technical detail, ImageField inherits from FileField. As it is stated in the documentation:

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

Therefore:

FieldFile.url

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

To display uploaded user files in development you need to change the urls.

这篇关于在模板中显示上传的图像 - Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆