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

问题描述:

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

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.

现在,当查看蔬菜的详细信息页面时,我想显示其图像,但是模板仅显示字符串'VegetableImage Object'来代替图像,甚至带有img标签.

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

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

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

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

有关更多技术细节,请 ImageField 继承自 FileField .在文档中声明 :

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

在模型*问FileField时,会为您提供FieldFile的实例作为访问基础文件的代理...

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

一个只读属性,可通过调用基础Storage类的url()方法来访问文件的相对URL.

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

查看更多