3
I have two selects, one for division and the other for groups. When the division is selected it has to bring in the second only the groups that are part of that division. In the url variable that picks the json I called python according to my view, but instead of this 4 it has to be id of the one that was selected earlier. At this line:var url = "{% url 'register:all_json' 4 %}" ;
<script>
$( document ).ready(function() {
$("select#id_divisao").change(function() {
if ($(this).val() == '') {
$("select#id_grupos").html("<option>Selecione uma divisão</option>");
$("select#id_grupos").attr('disabled', true);
} else {
var url = "{% url 'cadastro:all_json' 4 %}" ;
$.getJSON(url, function(grupos) {
var options = '<option value="">Select uma divisão</option>';
for (var i = 0; i < grupos.length; i++) {
options += '<option value="' + grupos[i].pk + '">' + grupos[i].fields.grupo + '</option>';
}
$("select#id_grupos").html(options);
$("select#iid_grupos option:first").attr('selected', 'selected');
});
}
});
});
</script>
py views.:
def all_json_grupos(request, idDivisao):
json_grupos = serializers.serialize("json", Grupo.objects.filter(divisao_id=idDivisao))
return HttpResponse(json_grupos)
I go through the url and show me the groups according to the division I put, I just need to make it work in select
Can take the value of the previous select by its name?
– Marlysson
I’m picking by the id, because in the group table I have the division id
– Bianca C.
Well, once you get that id, the problem ( I see ) is how to inject it into the Django url.. Here’s an alternative.. var url = "{% url 'urlpattern_name' {id} %}". replace('{id}', seu_id); With this pass your id to string and then to getJSON.. Remember that Django has a class to serialize Jango objects for json.. a Jsonresponse
– Marlysson
Thanks Marlysson, I was able to solve by adapting the method you sent me, thus: var url = "{% url 'cadastre:all_json' 4 %}". replace(4, $(this). val());
– Bianca C.
Oops, for nothing. I’m just going to put the suggestion as an answer, so other people can build on.
– Marlysson