How to access data from a dynamic imput of a form with Django?

Asked

Viewed 377 times

2

I am participating in a project in which we are using Django. I created a form with two initial fields and can add more dynamically using javascript.

<div class="form-group">
            <div class="panel-title"><b>Informe os Criterio:</b></div>
        </div>
        <div>
            <input type="button" id="add_field_criterio" value="adicionar">
        </div>
        <div id="grupo_criterio">
            <div>
            <label for="criterio" class="control-label">Criterio:</label>
                <input type="text" required  name="criterio[]" placeholder="Informe o nome do criterio">
            </div>
            <div>
                <label for="criterio" class="control-label">Criterio:</label>
                <input type="text" required name="criterio[]" placeholder="Informe o nome do criterio">
            </div>

$(document).ready(function() {
var campos_criterio_max = 10;
var campos_alternativa_max = 10;    //max de 10 campos
var x = 3; // campos iniciais
var y = 3;
$('#add_field_criterio').click (function(e) {
    e.preventDefault();     //prevenir novos clicks
    if (x <= campos_criterio_max) {
        $('#grupo_criterio').append('<div>\
        <label for="criterio" class="control-label">Criterio:</label>\
        <input type="text" required  name="criterio[]" placeholder="Informe o nome do criterio">\
        <a href="#" class="remover_campo_criterio btn btn-danger">Remover</a>\
        </div>');
        x++;
    }
});

// Remover o div anterior
$('#grupo_criterio').on("click",".remover_campo_criterio",function(e) {
    e.preventDefault();
    $(this).parent('div').remove();
    x--;
});

How I access the elements of the POST method since there will be no data persistence?

  • Can you explain what you want to get and when? You want the input values at the time of form Submit, is that it? the form is sent via html or you want to prevent sending and handling the data with Javascript?

  • I want to receive the form data. The javascript I posted is to control the amount of form inputs.

1 answer

0


Let’s say you want to access the list of criteria the user added:

  1. Remove the [] of criterio[]. When inputs are sent with same name a list is created automatically.

Now just access the view :

def foo(request):
       criterios = request.POST.get('criterio')
  • Thank you! I’ll test.

Browser other questions tagged

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