I am trying to reatain data from my db and pre-select a multi select using select2 and jinja2.
My jija2/html code:
<span class="input-group-addon">Relocate Where</span>
{% if not context.relocate_to %}
<input class="form-control" id="relocate_to" value="" type="hidden" name="relocate_to" data-placeholder="Choose province" />
{% else %}
{% for v in context.relocate_to|batch(9, ' ') %}
<input class="form-control" id="relocate_to" value="{{v}} " type="hidden" name="relocate_to" data-placeholder="Choose province" />
{% endfor %}
{% endif %}
my Js:
$.getJSON("{{'provinces.json'|route_url}}").success(function(data) {
$("#relocate_to").select2({
data:data,
multiple: true
maximumSelectionSize: 9
});
});
This only fills the multi select with 1 tag, this is wrong as there is 2 Provinces
in the database for this user, and there can be 9 Provinces selected.
I have looked at these question, but it doesn't help me much.
How can I achieve my goal of retaining the data with jinja2 and select2?
Would it be better retaining the data using jQuery?
I found an alternative way of doing what I wanted to do:
In my python code I create a dict with the data to create the select then I do this:
I hope this can help someone in the future.
Then I just initialize select2: