Using Django. In a template i want an image that if the user wants to change the photo, he just needs to click in the image already presented and then the file explorer is opened so that a new image can be chosen. Then the new image must be preview in the template in place of the old one temporarily.
the program is opening the file explorer, i choose the new image but the old image isn’t change and the new image isn’t displayed in any place of the html too
my code:
<script>
// Quando a imagem da pessoa for clicada
document.getElementById("imagem-pessoa").addEventListener('click', function() {
// Abrir o explorador de arquivos ao clicar no campo de arquivo oculto
document.getElementById("input-imagem").click();
});
// Quando uma nova imagem for selecionada
document.getElementById("input-imagem").addEventListener('change', function(event) {
// Capturar a nova imagem selecionada
const novaImagem = event.target.files[0];
// Atualizar temporariamente a imagem no HTML
const urlNovaImagem = URL.createObjectURL(novaImagem);
document.getElementById("imagem-pessoa").src = urlNovaImagem;
});
</script>
and the html
<img class="rectangle" id="imagem-pessoa" src="{{ pessoa.imagem.url }}" alt="Imagem da Pessoa">>
<input type="file" id="input-imagem" style="display: none;" accept="image/*">
it aren’t working
what i expected is: "a person registration page is loaded, receiving a number that searches the database and returns a person from the database. It then fills in some elements on the screen with the data found in the database table about that person. Among the people model objects there is a model.ImageField that stores a photo of each person." What I need is: I want the image found referring to the person that was searched for (in the people table) to be presented in the html, but at the same time I want it so that if the user wants to change the photo, he just needs to click on it of the image already presented and then the file explorer is opened so that a new image can be chosen. Once the new image has been chosen, the new image must be displayed in the html in place of the old one temporarily, but the replacement of the photo in the database must only be carried out after a submit button is clicked
2
Answers
I solve the problem
to make this functionality works in a template html in django, see this code
html
javascript
let photo = document.getElementById('imgPhoto');
let file = document.getElementById('flImage');
photo.addEventListener('click', () => {
file.click();
});
file.addEventListener('change', () => {
if (file.files.length <= 0) {
return;
}
let reader = new FileReader();
reader.onload = () => {
photo.src = reader.result;
}
reader.readAsDataURL(file.files[0]);
});
Try this code in index.html file: