<div style="display:inline-block;">
{% if widget.is_initial %}
<img src="{{widget.value.url}}" height="128" alt="{{widget.name}}" id="id_{{widget.name}}_img" />
{% if not widget.required %}
<input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}">
<label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label>{% endif %}<br>
{{ widget.input_text }}:{% endif %}
<input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %} onchange="previewImage(this)">
</div>
<script>
function previewImage(input) {
  if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        var id = input.getAttribute("id");
        if(document.getElementById(id+"_img")) {
          document.getElementById(id+"_img").setAttribute("src", e.target.result);
        } else {
          var img = document.createElement("IMG");
          img.src = e.target.result;
          img.height = 128;
          img.id = "id_{{widget.name}}_img";
          img.alt = "{{widget.name}}";
          input.parentNode.insertBefore(img, input);
          input.parentNode.insertBefore(document.createElement("BR"), input);
        }
      };
      reader.readAsDataURL(input.files[0]);
  }
}
</script>
