Python function together with html, how to reconcile?

Asked

Viewed 308 times

0

I have a select:

<select class="form-control">
    <option value="0" selected>Selecione uma opção</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
</select>

And just below, mixed, I have the following code on Python:

{% for objeto in objetos %}
    {% if objeto.escolha == 'opcao do select' %}
        FAÇA ISSO
    {% else %}
        FAÇA AQUILO
    {% endif %}
{% endfor %}

How do I save the selected value in select to be used in if of the code Python?

  • I believe that you wanted to take the value of select and make a change to the page, but python renders the page and sends it to the client machine, and only by making a new request could it take this value and then do some action, I believe that the best way to solve your problem is by making the change using javascript

2 answers

2


The template engine is not used to manipulate the DOM in real time. In this case, Javascript is used.

HTML:

<select class="form-control" id="select1" onchange="handleSelectChange()">
    <option value="0" selected>Selecione uma opção</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
</select>

<h1 id="text1"></h1>

JS:

var select = document.getElementById('select1');
var h1 = document.getElementById('text1');

function handleSelectChange(v)
{
    if(select.value == 1)
        h1.innerHTML = 'Selecionou a opção' + select.value.toString();
    else
        h1.innerHTML = 'Selecionou uma opção diferente de 1';

}

Nowadays, probably, no one uses pure javascript like I did above, recommend jQuery or a modern js framework like Vue.js and the like.

EDIT 1:

Remembering that all manipulation done via JS is on the front end, if you want to interact with the back end (Django I imagine), you can use Ajax.

-1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.