3

I am trying to preview image before uploading it to the html page. I am using django. This is my model

class Product(models.Model):
    
    image = models.ImageField(upload_to='uploads/')
    thumbnail = models.ImageField(upload_to='uploads/')

    class Meta:
        ordering = ['-date_added']

this is my form.py

class ProductForm(ModelForm):
    class Meta:
        model = Product
        fields = ['image']

and this is my html page

<form method="post" action="." enctype="multipart/form-data">
                        {% csrf_token %}
                
                        {{ form.non_field_errors }}
                        
                        
                        <div class="fieldWrapper">
                            {{ form.image.errors }}
                            <br>
                            <label for="{{ form.image.id_for_label }}"><br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;Image: &nbsp;</label>
                            {{ form.image }}
                       </div>
                       <div class="field">
                            <div class="control" style="margin-bottom: 3%">
                                <button class="btn btn-theme" style="float:right;">SUBMIT</button>
                            </div>
                       </div>
                       </form>


I am able to upload and display the image in the html page but i want it so that before i upload i can see the image i am trying to upload. How can i do that?

newbieperson
  • 79
  • 2
  • 7
  • for this feature you can only use front-end tools like js in your template: https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded – Leyla Krz Nov 16 '21 at 07:22
  • that doesnt work because it onchanging in input but my {{form.image}} already is uploading the image. – newbieperson Nov 16 '21 at 08:49

1 Answers1

1

If you are trying to upload an image for the first time, you can use createObjectURL, which takes the object present in HTML File upload.

<Image id="imagePreviewOne" thumbnail src="URL.createObjectURL(--get image object using selector--)"/>

If you are previewing images already present in Django models, then you have to use URL of the image in Image HTML tag.

<Image id="imagePreviewTwo" thumbnail src="URL to image present in django models" />

CreateObjectURL : https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

File Upload: https://www.w3schools.com/howto/howto_html_file_upload_button.asp

B.Anup
  • 585
  • 4
  • 6
  • CreatObjectURL works if i do But then i cannot save that data – newbieperson Nov 16 '21 at 08:54
  • Try this, https://stackoverflow.com/questions/22087076/how-to-make-a-simple-image-upload-using-javascript-html – B.Anup Nov 16 '21 at 09:08
  • still doesn't work – newbieperson Nov 16 '21 at 09:19