View an Image Using Django CreateView Before Submitting

这一生的挚爱 提交于 2019-12-13 03:26:43

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/57064354/view-an-image-using-django-createview-before-submitting

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