How to call the previous select id

3

I have 2 selects, one division and the other group. 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 takes json I called python according to my view, but instead of that 4 it has to be the id of the one that was previously selected. In this line: var url="{% url 'signup: 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>

views.py:

def all_json_grupos(request, idDivisao):
    json_grupos = serializers.serialize("json",  Grupo.objects.filter(divisao_id=idDivisao))
    return HttpResponse(json_grupos)

I enter through the url and it shows me the groups correctly according to the division that I put, I just need to make it work in select

    
asked by anonymous 13.09.2017 / 16:17

1 answer

2

Well, your problem as discussed in the comments is how to put the value of id that you are already able to capture from html.

For this you can do a "hack" by creating a django url in simple string in javascript, replace the value that you and then pass to some js function to make the calls .. It would look like this:

....código anterior

var url = "{% url 'cadastro:all_json' id %}".replace('id', $(this).val())
$.getJSON(url, function(grupos) {
    ....continue seu código
}

....continuação do código
    
14.09.2017 / 16:07