0

Yesterday, using this solution View an Image Using Django CreateView Before Submitting I was able to figure out how to display an image when a user clicks on the choose file button in my Django project. However, I can't figure out how to now save the image when the user submits the form. I realize the solution I am using is leveraging the HTML URL to display the image using Javascript.

When I am using an approach for the use to attach an image and then submit the form without displaying the image first, this works fine. However, when I use the solution referenced above, it is not capturing the image.

This works...

<div>
  <h2>Photo: </h2>
</div>

<div>
  {{ form.image }}
</div>

However, when I try to leverage this instead....from the prior solution...

<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />

And using Javascript...

  function readURL(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        $('#blah')
          .attr('src', e.target.result)
          .width(150)
          .height(200);
      };
      reader.readAsDataURL(input.files[0]);
    }
  }

The file displays, but I can't figure out how to save it to the database upon user submit.

I tried to use various solutions documented here...Django: add image in an ImageField from image url But no luck so far. Thanks in advance for any thoughts.

Steve Smith
  • 1,019
  • 3
  • 16
  • 38

1 Answers1

0

And it turned out to be so simple!!! It's simple when you know the answer BTW..

<input type='file' name="django_form_field_name" onchange="readURL(this);" />

Making sure the input name matched the django form name was the way to get the image URL into the database with the proper location.

Steve Smith
  • 1,019
  • 3
  • 16
  • 38