0

I have a Django CreateView that works as expected. I allow the user to attach a photo and then after they click Submit, the view captures the image as expected. However, I am trying to figure out if there is a way, using CreateView, to show the image that has been captured. As of right now, it shows the file name, but I am trying to get it to show the image instead. I tried a variation of this SO question, but it is not for CreateView and I can't figure out how to translate it. Render image without saving

Here is my simple example, that works as expected.

My Model...

class NewAuthor(models.Model):

image = models.ImageField(upload_to='images/',default='images/pic.jpg')

My view....

class CreateNewAuthorView(CreateView,NeverCacheMixin):
    model = NewAuthor
    form_class = CreateNewAuthorForm
    template_name = 'create_new_author.html'

My form...

class CreateNewAuthorForm(forms.ModelForm):

class Meta:
    model = NewAuthor
    fields = ['image',]

My HTML...

<form method="POST" enctype="multipart/form-data">

{% csrf_token %}

    <div class="picture">
      {{ form.image }}
    </div>

How can I incorporate code that will allow the image that was uploaded to actually be displayed before the user hits submit?

Thanks in advance for any suggestions.

Steve Smith
  • 595
  • 2
  • 6
  • 24

1 Answers1

2

If you are using Django templates than it's Server-Side Rendering (SSR).

Which mean the HTML pages that are served are rendered at the backend and then sent to the browser. You have to use javascript to do what you are trying to do.

A Javascript example to display the image/file that has been attached. Here is a code to do something like that

HTML Code

<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>

JS

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 solution was taken from this answer

Adnan Sabbir
  • 171
  • 1
  • 11