I am trying to populate a form with a Select element using ajax and Django.
The code I have is the following, but it only shows me one result, when sometimes there are more results.
const cliente = document.querySelector('#selectClienteID')
cliente.addEventListener('change', (event) => {
event.preventDefault();
$.ajax({
type: "POST",
data: $("#addPresupuesto").serialize(),
url: '{% url "systemapp:add_presupuesto" %}',
success: function (data) {
const form_label = '<label for="vehiculo">Seleccionar vehículo</label>'+'<select name="vehiculo" class="form-control" id="vehiculo">'+`<option value="" selected="">Seleccionar vehículo</option>`
for (x in data.cars) {
var car = data.cars[x]
console.log(car['marca'])
const option = `<option value="`+car['id']+`">`+car['marca']+`</option>`
$('#showVehiculos').html(form_label + option);
}
},
error: function () {
console.log('Fail')
},
})
})
From my views I send a list with a dictionary and the values to show:
form = AddPresupuesto()
if request.method == 'POST':
if request.is_ajax():
cliente = Cliente.objects.get(id=request.POST.get('cliente'))
vehiculos = Vehiculo.objects.filter(cliente=cliente)
cars_list = []
for car in vehiculos:
cars = {}
cars['id'] = car.id
cars['marca'] = f'{car.marca} {car.modelo}'
cars_list.append(cars)
return JsonResponse({'cars':cars_list})
but when showing the results in the template only one is shown
It should be two in this case, as shown in the console:
Could someone give me a hand?
regards
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…