[Solved]-Django – How can I display a photo saved in ImageField?

21👍

Sorry, I didn’t pay close enough attention to the context of field. The “field” you get from the for loop is a specialized wrapper that includes other data about the field for the purposes of constructing the form. It’s not the field on the model itself, just a representation of it for the purposes of the form.

To get the current value of profile_pic, you need to use the form’s instance:

<img src="{{ form.instance.profile_pic.url }}" />

{{ MEDIA_URL }} is unnecessary when using the url attribute, since it automatically appends MEDIA_URL.

8👍

This works for me:

    {% for field in form %}
    <p>
        {{ field.errors }}
        {{ field.label_tag }}
        {% if field.field|get_type == "django.forms.fields.ImageField" and field.value %}
            <br/><img src="{{ field.value.url }}" width="240"></img></br>
        {% endif %}
        {{ field }}
    </p>
    {% endfor %}

get_type is a templatetag defined as:

from django import template

register = template.Library()

@register.filter
def get_type(value):
    t = type(value)
    return t.__module__ + "." + t.__name__

Leave a comment