Add Django template logic to a select created programmatically from Javascript

Viewed 22

Let's say I have an empty select like this:

<select name="select_name" class="selectpicker show-tick w-100" required>
</select>

When the page loads, an ajax function is called and populates the select:

$.ajax({
    type: 'GET',
    data : { ... },
    url: "../../some_view/",
    headers: {
        'X-CSRFToken': csrftoken
    },
    success: function (response) {
        $("[name='select_name']").selectpicker('destroy');
        var item_list = "";
        for(var i = 0; i < response.length; i++) {
            item_list += '<option value='+response[i].pk+'>'+response[i].fields.reference_code+'</option>'
        }
        $("[name='select_name']").html(item_list);
        $("[name='select_name']").selectpicker();
    },
    error: function(xhr, status, error) {
        console.log(xhr.responseText);
    }
})

This would create a 'flat' select. How could I add Django template logic to that dynamically created select?

For instance, I would like the select populated after the ajax call to have something like this:

<select name="select_name" class="selectpicker show-tick w-100" required>
  {% for item in items %}
  {% if item.reference_code|stringformat:'s' == values.reference_code|stringformat:'s' %}
    <option value="{{ item.id }}" selected>{{ item.reference_code }}</option>
  {% else %}
    <option value="{{ item.id }}">{{ item.reference_code }}</option>
  {% endif %}
  {% endfor %}
</select>

Any help will be highly appreciated

0 Answers
Related