简体   繁体   中英

How do i use use javascript on form upload button django

What I want to achieve:

My requirement is to first display the image on the template/html page then upload it in the database, for displaying the image on the page I am using javascript.

So how do i use {{form.image}} in javascript button?


Other side details:

For uploading the image I am using Django forms inbuilt button of {{form.image}} by clicking one button I should be able to display and upload the image

Below is the code for reference

form.py

from django import forms 

from .models import Boneage

class BoneageForm(forms.ModelForm): 
    class Meta: 
        model = Boneage 
        fields = ('gender', 'age','images')

JavaScript code

<script>
      const wrapper = document.querySelector(".wrapper");
      const fileName = document.querySelector(".file-name");
      const defaultBtn = document.querySelector("#default-btn");
      const customBtn = document.querySelector("#custom-btn");
      const cancelBtn = document.querySelector("#cancel-btn i");
      const img = document.querySelector("img");
      let regExp = /[0-9a-zA-Z\^\&\'\@\{\}\[\]\,\$\=\!\-\#\(\)\.\%\+\~\_ ]+$/;
      function defaultBtnActive(){
        defaultBtn.click();
      }
      defaultBtn.addEventListener("change", function(){
        const file = this.files[0];
        if(file){
          const reader = new FileReader();
          reader.onload = function(){
            const result = reader.result;
            img.src = result;
            wrapper.classList.add("active");
          }
          cancelBtn.addEventListener("click", function(){
            img.src = "";
            wrapper.classList.remove("active");
          })
          reader.readAsDataURL(file);
        }
        if(this.value){
          let valueStore = this.value.match(regExp);
          fileName.textContent = valueStore;
        }
      });
    </script> 

How do i use this java script code in the Django form button?

{{form.images}}
   <button onclick="defaultBtnActive()" id="custom-btn">  </button>

Django specifies an id for every input method so go to inspect and see what is the id of the image input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM