Search code examples
djangoimagefield

Preview the photo after selecting the file in Django


I can not find information on this topic. How to easily create a preview of the photo in Django after selecting it (before saving the form). As on the video below:

enter image description here

https://youtu.be/HVd2v1aUED0

Is there any simple plugin that will enable this? I think that sending photos in this mode is very popular (that is, a thumbnail of the photo, before saving the whole model).


Solution

  • In your django template you can write a small script to display the preview of the image selected by the user. In template:

    <!-- To display image -->
    <img id="myimage" src="xyz" > </div>
    
    <!-- To upload new image -->
    <input name="images" onchange="readURL(this);" type="file" accept="image/*"/>
    

    In the same template:

    <script>
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
    
            reader.onload = function (e) {
                $('#myimage').attr('src', e.target.result);
            };
    
            reader.readAsDataURL(input.files[0]);
        }
    }
    
    </script>