Django: Trying to populate a dropdown using Javascript

curiousIT :

I have two dropdowns and I'm trying to populate the second one using Javascript when the first one changes. It should be populated from the database values contained in 'departements' variable of my views.py file.

I found some code on the web but it didn't work when I tried to apply it to my case. I have next to 0 knowledge in Javascript, so no idea if I'm even on the right path.

Below are more details about my files:

models.py

class data_immo(models.Model):
    id = models.AutoField(primary_key=True)
    insee_dep = models.IntegerField(db_column='INSEE_DEP', blank=True, null=True) 
    nom_reg = models.TextField(db_column='NOM_REG', blank=True, null=True)  

    class Meta:
        managed = True
        db_table = 'immo'

views.py

def MyView(request):

    query_results = data_immo.objects.all()
    regions = data_immo.objects.values_list("nom_reg", flat=True).distinct()
    departements = data_immo.objects.values_list("insee_dep", flat=True).distinct()

    query_results_dict = {
        'query_results': query_results,
        'regions': regions,
        'departements': departements,
    }

    return render(request,'home.html', query_results_dict)

home.html

<select id="reg" name="reg" onChange="populate2()"> 
 {% for item in regions %}
 <option val="{{ item.nom_reg }}"> {{ item.nom_reg }} </option>    
 {% endfor %}
</select>

<select id="dep" name="dep"></select>

<script type="text/javascript">
 function populate2(){      
 $('.dep').append('<option>' + departements[0].insee_dep  + '</option');
      }
</script>

I need the populate2() function to update the 'dep' dropdown. The function is obviously wrong, but I don't know where exactly. Thanks in advance!

Pablo Tato Ramos :

(DISCLAIMER: It's been a while since I last used Django)

Some things I notice are:

  1. You're querying the element as .dep rather than #dep. . queries the class attribute of the HTML element, and # queries its id.

  2. The closing tag for the options (</option>) has a typo

  3. departements exists only on the server side. You can't use it as a variable directly from javascript.

If I'm understanding your question right, you might want something like the following, if using browser APIs

function populate2() {
    let depSelect = document.querySelector('#dep');
    let option;
    {% for d in departements %}
    option = document.createElement("OPTION");
    option.innerText = "{{ d.insee_dep }}";
    option.value = "{{ d.insee_dep }}";
    depSelect.appendChild(option);
    {% endfor %}
}

or in jQuery

function populate2() {
    let depSelect = $('#dep');
    {% for d in departements %}
    $($.parseHTML('<option></option>'))
        .text("{{ d.insee_dep }}")
        .val("{{ d.insee_dep }}")
        .appendTo(depSelect);
    {% endfor %}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29975&siteId=1