0

我正在使用复选框,问题是我只能获得第一个值而不是我检查的所有值,我做错了什么。

视图.py

def solicitud_laboratorio(request):
  if request.method == 'POST':
    formulario = Solicitud_lab(request.POST)
    if formulario.is_valid():
        formulario.save()
        medicinas = []
    for i in range(len(request.POST.getlist('examen'))):
        data = {
            'nombre_examen': request.POST.getlist('examen')[i],
            'credencial_miembro': request.POST['laboratorio_credencial']
        }
        print data
        medicina = examenlab_form(data)

        if medicina.is_valid():
            medicina.save()
            medicinas.append(medicina)
            messages.success(request, 'Alta Exitosa!')
        return HttpResponseRedirect('')
    else:
        messages.success(request, 'Se presento un error al dar de alta')
else:
    medicinas = [examenlab_form()]
    formulario = Solicitud_lab()
return render_to_response('sol_laboratorio.html', {'medicinas': medicinas, 'formulario': formulario},
                          context_instance=RequestContext(request))

这是模板的一部分,我在其中定义列表

 <table style="width:20%; margin-left:70px " align="left" width="95%" cellspacing="0"     cellpadding="5" border="0">
    <tr>
        <td bgcolor="#85D5EF">Hematologia</td>
    </tr>
{% for examen in medicinas %}
    <tr>
        <td><input type="checkbox" name="examen" value="BIOMETRIA HEMATICA"> Biometria Hematica</td>
    </tr>
{%endfor%}
    <tr>
        <td><input type="checkbox" name="examen" value="VEL DE SEDIMENTO GLOBULAR"> Vel De Sedimento Globular</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="examen" value="RETICULOCITOS"> Reticulocitos</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="examen" value="COOMBS DIRECTO"> Coombs Directo</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="examen" value="COOBS INDIRECTO"> Coombs Indirecto</td>
    </tr>
4

1 回答 1

1

因为您return在仅处理第一个值后使用语句退出函数:

for i in range(len(request.POST.getlist('examen'))):
    data = {
        'nombre_examen': request.POST.getlist('examen')[i],
        'credencial_miembro': request.POST['laboratorio_credencial']
    }
    print data
    medicina = examenlab_form(data)

    if medicina.is_valid():
        medicina.save()
        medicinas.append(medicina)
        messages.success(request, 'Alta Exitosa!')
    return HttpResponseRedirect('')

将该return语句移出循环。您还应该只循环.getlist()调用,此处无需使用诱导:

for exam in request.POST.getlist('examen'):
    data = {
        'nombre_examen': exam,
        'credencial_miembro': request.POST['laboratorio_credencial']
    }
    print data
    medicina = examenlab_form(data)

    if medicina.is_valid():
        medicina.save()
        medicinas.append(medicina)
        messages.success(request, 'Alta Exitosa!')

return HttpResponseRedirect('')
于 2013-09-30T20:43:40.617 回答