Django - How can I display a photo saved in ImageField?

≯℡__Kan透↙ 提交于 2019-11-28 07:45:40

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.

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