Displaying uploaded images in the template - Django

二次信任 提交于 2019-12-03 21:50:26
Wtower

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.

You're trying to output the model itself, rather than the image field on the model.

You probably want to use a different variable name in your for loop, or it may get confusing later trying to work out what "vegetable" refers to.

Try

{% 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 %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!