0
Hello guys, good afternoon, I need to use a JS variable, being it the type Boolean in the Django template
but I don’t know how to do it.
Example of what I want to do:
<!DOCTYPE html>
<html>
<body>
<script>
let showMessage = false;
</script>
{% if showMessage %}
faça isso
{% else %}
faça aquilo
{% endif %}
</body>
</html>
I know that python is very simple, but I’m using a web service in JS
registrations.js:
// RETORNO DA API EM JSON - AUTOCOMPLETE DOS INPUT
let showMessage = false;
function callback(content) {
if (!("erro" in content)) {
const Inputs = document.querySelectorAll(`form input`);
Inputs[2].value = (content.logradouro);
Inputs[4].value = (content.complemento);
Inputs[5].value = (content.bairro);
Inputs[6].value = (content.localidade);
Inputs[7].value = (content.uf);
} else {
formClean();
showMessage = true; <---- aqui que mudo o valor da variavel
}
}
// FAZ BUSCA DO CEP - ONBLUR
function searchByCep() {
const cep = document.querySelector(`#id_zip_code`);
if (cep.value != "") {
let script = document.createElement(`script`);
script.src = 'https://viacep.com.br/ws/' + cep.value + '/json/?callback=callback';
document.body.appendChild(script);
}
};
And why don’t you use your own
if
javascript?– Woss
@Andersoncarloswoss why in case I want to display an error message when
showMessage = true
remembering that I want to use the variable in the Django template– Raphael Melo De Lima
But it doesn’t make sense. Python runs on the server, JS on the client. If you just want to display an error message when it is
true
, you can do this only with Javascript. Read about the concepts of client-side and server-side.– Woss
@Andersoncarloswoss understand that I could do it using
document.createElement()
, but in my opinion it would not be the best way to do it... but it was worth– Raphael Melo De Lima
It will only be easier if you set the value of the variable also by Python. Otherwise, how will it know the value? You will have to parse the HTML to be able to extract the information.
– Woss
In the example code
showMessage
never changes. In real code what would change this value? Some Python variable or some jQuery action on the page?– fernandosavio
@fernandosavio I edited the question to be easier to understand, I will try to use
document.createElement()
, but I am open to new knowledge– Raphael Melo De Lima
I would create an element intended only for feedback in Python and JS just change its content with
innerHTML
or affines and then make it visible. .– fernandosavio