I am doing tests for a form that I must do and the most important thing are two combo boxes, where the second one depends on the choice of the first one. I have done many tests with different methods but I have not achieved the result I need.
I currently have these files in my project:
forms.py:
from django import forms
from .models import TblInfoCatalogoValores
from .choices import tupla_lista, tupla_lista_2
class pruebaForm(forms.Form):
multiple_choice = forms.ChoiceField(
label=u"Select multiple",
choices=tupla_lista,
widget=forms.widgets.Select,
initial=(c[0] for c in tupla_lista)
)
multiple_choice_2 = forms.ChoiceField(
label=u"Select multiple 2",
choices=tupla_lista_2,
widget=forms.widgets.Select,
initial=(d[0] for d in tupla_lista_2)
)
For the options I have a choices.py file with the following:
from .models import TblInfoCatalogoValores
#-----------------------Primer Select-----------------------
tupla = []
query_1 = TblInfoCatalogoValores.objects.filter(id_catalogo = 22).values_list("valor", "des_valor")
for i in query_1:
tupla.append(i)
tupla_lista = tuple(tupla)
#-----------------------Segundo Select-----------------------
tupla_2 = []
query_2 = TblInfoCatalogoValores.objects.filter(id_catalogo = 23).values_list("valor", "des_valor")
for e in query_2:
tupla_2.append(e)
tupla_lista_2 = tuple(tupla_2)
The model I'm using is this: models.py
class TblInfoCatalogoValores(models.Model):
id_valor = models.AutoField(db_column='ID_VALOR', primary_key=True)
id_catalogo = models.ForeignKey(TblInfoCatalogoId, models.DO_NOTHING, db_column='ID_CATALOGO')
valor = models.CharField(db_column='VALOR', max_length=10)
des_valor = models.CharField(db_column='DES_VALOR', max_length=150, blank=True, null=True)
val_1 = models.CharField(db_column='VAL_1', max_length=20, blank=True, null=True)
val_2 = models.CharField(db_column='VAL_2', max_length=20, blank=True, null=True)
val_3 = models.CharField(db_column='VAL_3', max_length=20, blank=True, null=True)
val_4 = models.CharField(db_column='VAL_4', max_length=20, blank=True, null=True)
val_5 = models.CharField(db_column='VAL_5', max_length=20, blank=True, null=True)
val_6 = models.CharField(db_column='VAL_6', max_length=20, blank=True, null=True)
val_7 = models.CharField(db_column='VAL_7', max_length=20, blank=True, null=True)
orden = models.IntegerField(db_column='ORDEN', blank=True, null=True)
class Meta:
managed = False
db_table = 'TBL_INFO_CATALOGO_VALORES'
And what I'm using from this table is this. Where ID_CATALOGO = 22
, would be the data of the first select and ID_CATALOGO = 23
are the data that depend on the first select:
I have this in my views.py :
from .forms import pruebaForm
def pruebaViewForm(request):
formulario = pruebaForm()
if request.method == 'POST':
formulario = pruebaForm(request.POST)
if formulario.is_valid():
url = reverse('inicio')
return HttpResponseRedirect(url)
return render(request, 'pruebaForm.html',
{'formulario_prueba': formulario}
)
In my ajax.py I have problems, and I do not know how to solve them ... I do not know how to compare the values:
from django.http import JsonResponse
from .models import TblInfoCatalogoValores
from .choices import tupla_lista, tupla_lista_2
def get_sub_objetivo(request):
objetivo_id = request.GET.get("objetivo_id")
sub_objetivos = tupla_lista_2
options = '<option value = "" disabled>*********</option>'
for sub_objetivo in sub_objetivos:
options += '<option value = "%s">%s</option>' % (
sub_objetivo.val_1,
sub_objetivo.valor
)
response = {}
response['sub_objetivos'] = options
return JsonResponse(response)
For the ajax function I am using this in my urls.py file:
url(r'^ajax/get_sub_objetivo/$', get_sub_objetivo, name='get_sub_objetivo')
And in my template.html I have this:
<h1>Formulario de prueba</h1>
<form method="POST">
{% csrf_token %}
<div>
{{ formulario_prueba.multiple_choice.label_tag }}
{{ formulario_prueba.multiple_choice}}
</div>
<div>
{{ formulario_prueba.multiple_choice_2.label_tag }}
{{ formulario_prueba.multiple_choice_2}}
</div>
<input type="submit" name="Enviar">
</form>
<script type="text/javascript">
//Le doy la función de onchange al select de sub-objetivos.
$(document).ready(function(){
$("#id_multiple_choice").on("change", getSubObjetivos);
});
function getSubObjetivos(){
var id_select_1 = $("#id_multiple_choice").val();
if (id_select_1) { alert(id_select_1)} //esto es una prueba
if (id_select_1) {
$("#id_multiple_choice_2").html("");
alert("Entro!!!!!!!!"); //Esto es una prueba
var request = $.ajax(
{
type: "GET",
url: "{% url 'get_sub_objetivo' %}",
data: {
"objetivo_id": id_select_1
},
success: function (response) {
$("#id_multiple_choice_2").html(response.sub_objetivos);
}
}
);
request.done(function(response){
alert("Regreso"); //Esto es una prueba
$("#id_multiple_choice").html(response.sub_objetivos);
$("#id_multiple_choice_2").trigger("change");
});
}
else {
alert("Error"); //esto es una prueba
$("#id_multiple_choice_2").html("<option value='' selected='selected'>-------</option>");
$("#id_multiple_choice_2").trigger("change");
}
}
</script>
This I did by guiding me on this example
Thanks for your answers.