] 3
Form that tells me what is the value of transportation with DJANGO. when selecting the school and the place where you live, I see the rate (value)
For this you must use some ajax, jquery similar to the dependent combos. First of all I suggest some slight changes in your models:
class Colegio(models.Model):
nombre = models.CharField(max_length=100)
def __str__(self):
return self.nombre
......
......
class Destino(models.Model):
nombre = models.CharField(max_length=100)
def __str__(self):
return self.nombre
......
......
class Tarifa(models.Model):
colegio = models.ForeignKey(Colegio, on_delete=models.CASCADE)
destino = models.ForeignKey(Destino, on_delete=models.CASCADE)
precio = models.FloatField()
def __str__(self):
return self.precio
......
......
As you can see in the models it is not necessary to define the id, since by default Django already does it by id and puts it with the name id and autoincrementable, also another change would be change:
cole_name, target_name
by:
name in this way it is clearer and thus stipulates most manuals and basic rules of database design and analysis. in your html:
<select name="colegio" id="colegio" onchange="consultarPrecio();">
<option value="" select disabled>Seleccione</option>
{% for colegio in contratos %}
<option value="{{ colegio.pk }}">{{ colegio.nombre }}</option>
{% endfor %}
</select>
<select name="destino" id="destino" onchange="consultarPrecio();">
<option value="" select disabled>Seleccione</option>
{% for destino in destinos %}
<option value="{{ destino.pk }}">{{ destino.nombre }}</option>
{% endfor %}
</select>
<input type="text" name="tarifa" id="tarifa">
If you look at what is done is add the onchange event, and through javascript I get these values and consult in the Tarifa model, the Javascript code would be something like this:
function consultarPrecio(){
//obtengo los valores de mis select y valido que hayan sido seleccionados
var colegio = $("#colegio").val();
if(colegio == "" || colegio == null){
alert("seleccione el colegio !!");
return false;
}
var destino = $("#destino").val();
if(destino == "" || destino == null){
alert("seleccione el destino !!");
return false;
}
//token
var csrftoken = getCookie('csrftoken');
$.ajax({
type: "GET",
url: "consultar_tarifa",
data:{
csrfmiddlewaretoken : csrftoken,
colegio:colegio,
destino:destino
},
dataType: "json",
success: function(data) {
codigo = data.resultado;
tarifa_data = data.precio[0];
if(codigo=='ok_select'){
$("#tarifa").val(tarifa_data.precio);
}
},
error: function( jqXHR, textStatus, errorThrown ) {
if (jqXHR.status === 0) {
alert('Error al intentar Conectarse: Verifique su conexion a Internet.');
} else if (jqXHR.status == 404) {
alert('La Pagina solicitada no fue encontrada [404]');
} else if (jqXHR.status == 500) {
alert('Erro Interno [500]');
} else if (textStatus === 'parsererror') {
alert('Error en el retorno de Datos. [parseJson]');
} else if (textStatus === 'timeout') {
alert('Tiempo de Espera agotado');
} else if (textStatus === 'abort') {
alert('Solicitud Abortada. [Ajax Request]');
} else {
swal('Error desconocido: ' + jqXHR.responseText);
}//end if
}//end error
});
}//end function consultarPrecio
Your urls.py:
url(r'^consultar_tarifa', ConsultarTarifa, name='consultar_tarifa'),
in your views.py:
def ConsultarTarifa(request):
if request.method == 'GET':
colegio = request.GET['colegio']
destino = request.GET['destino']
precio = Tarifa.objects.values().all().filter(colegio=colegio, destino=destino)
precio_list = list(precio)
data = {
'resultado': 'ok_select',
'precio': precio_list
}
return HttpResponse(json.dumps(data), content_type="application/json")
As you can analyze what I do is get the values of your select (school, destination) by its id and then send them to the views x ajax where I make a simple query and return the answer and I put it in a input (rate) mediate the id. There are more ways, I hope it serves you and can guide you.suerte!
Note .- When you are called by ajax to django you must include the django token as stipulated in the documentation .. review it: ajax django