具有相同名称的多个输入可写入数据库

时间:2019-10-19 01:00:09

标签: javascript html django

我有一个表单,并且具有多个具有相同名称的字段,我需要在Django视图中获取此数据并将其写入数据库。现在,我只是试图获取HTML数据并在视图中呈现,但是仅显示HTML表单的最后一个值。

查看

def agenda_padrao(request):
    inicio = request.POST['inicio']
    fim = request.POST['fim']
    idempresa = request.POST['id']
    if request.POST:
        for i in inicio:
            print(i)
    return render(request, 'core/agenda.html')

agenda.html

<form method="POST" action="/agenda/padrao/">{% csrf_token %}
    <div class="modal-body">
        <div class="row ">
            <h3>Horários</h3><br/>
            <a class="btn btn-success" href="javascript:void(0)" id="addInput">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
            </a>
        </div>
        <div id="dynamicDiv">
            <div class="row col-12">
                <input type="time" class="form-control form-control" id="inicio" name="inicio[]" style="width: 150px; margin-right: 10px;">
                <input type="time" class="form-control form-control" id="fim" name="fim" style="width: 150px;">
                <input type="hidden" name="id" value="{{ user.id_empresa }}">
            </div>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
        <button type="submit" class="btn btn-primary">Confirmar Horário Padrão</button>
    </div>
</form>

Javascript添加字段

$(function () {
        var scntDiv = $('#dynamicDiv');

        $(document).on('click', '#addInput', function () {
            $('<p>'+
                '<input type="time" class="form-control form-control" id="inicio" name="inicio" style="width: 150px; margin-right: 10px;">'+
                '<input type="time" class="form-control form-control" id="fim" name="fim" style="width: 150px; margin-right: 10px;">' +
                        '<a class="btn btn-danger" href="javascript:void(0)" id="remInput">' +
                            '<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>' +
                        '</a><br/>'+
                        '</p>').appendTo(scntDiv);
                        return false;
                        });
                        $(document).on('click', '#remInput', function () {
                        $(this).parents('p').remove();
                        });
                        });

1 个答案:

答案 0 :(得分:0)

您可以获取视图中输入值的列表:

inicio = request.POST.getlist('inicio[]')