Displaying uploaded images in the template - Django

前端 未结 2 1204
一整个雨季
一整个雨季 2021-01-03 08:34

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

相关标签:
2条回答
  • 2021-01-03 09:06

    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 %}
    
    0 讨论(0)
  • 2021-01-03 09:13

    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.

    0 讨论(0)
提交回复
热议问题