Run Python code by calling for a Django form

Asked

Viewed 414 times

1

good afternoon.

I’m starting to study Python and Django. By way of study I wrote a code in Python that receives a value and a date and makes the update by TJLP. This worked perfectly.

As the next step I created a form in Django so that the user can enter the value and date and request the correction by pressing a button. At that moment I call a view that should receive value/date and return the updated value, but I don’t know how to make the view call my code.

In advance I appreciate the help.

1 answer

0


TL;DR

If I understand correctly, just check in the view if your request uses the POST method, if yes, do the necessary processing and return the resulated. In the example below I create a template that asks for a date and a value, after the user’s submission, the view takes the value, multiplies by 2 and returns. The view, from the user’s first submission, shows what was typed in the previous submission and displays the value "corrected" (multiplied by 2):

In views.py:

from django.shortcuts import render

def home(request):

    data = None
    valor = None
    new_valor = None

    if request.method=='POST':
        data = request.POST['data']
        valor = request.POST['valor']
        new_valor = int(valor)*2
        # Faça aqui o que vc for precisos com os dados recebidos

    return render(request, 'main/index.html', {'data': data, 'valor': valor, 'new_valor': new_valor})

In the template (in this case, index.html):

<form method="POST">
    {% csrf_token %}
    <label for="data">Data:</label>
    <input id="data" type="date" name="data" value="" /><br>
    <label for="valor">Valor:</label>
    <input id="valor" type="number" name="valor" value="" /><br>
    <input type="submit">

    {% if data != None %}
        <br><br>
        <p>
            Sua última digitação:<br>
            Data Inicial: {{data}}<br>
            Valor: {{valor}}<br>
            Valor Corrigido: {{new_valor}}

        </p>
    {% endif %}
</form>

Presentation of the template after the first submission (Ubmit):

Execucao template django repl.it

See working on repl.it.

  • It worked perfectly. Thank you very much.

Browser other questions tagged

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