I am trying to adapt an already working application in Django, but I am quite new to this environment and I am not the original developer so I may have some conceptual errors, but I have not found a way to solve the problem.
I have a django model which references a client list:
clients = models.ManyToManyField(
Client,
blank=True,
verbose_name=_('Clients'),
related_name='clients',
)
It is being feed in the admin using the autocomplete feature, obtaining the client data from the other table. This is working perfectly.
I want to preload some data based on a select dropbox I have included in the form. On change of the select box, I want to include some values on this manytomany field.
I am using jquery to add values to the field, and as far as I have found, I need to add the client references in two places:
Add the name and the Id in a Select
<select name="clients" id="id_clients" class="admin-autocomplete select2-hidden-accessible"
data-ajax--cache="true" data-ajax--type="GET" data-ajax--url="/en/admin/client/client/autocomplete/"
data-theme="admin-autocomplete" data-allow-clear="true" data-placeholder=""
multiple="" tabindex="-1" aria-hidden="true">
<option value="2355">Client1</option>
</select>
Add the name in the unordered list (ul) as a new li.
<ul class="select2-selection__rendered">
<span class="select2-selection__clear">×</span>
<li class="select2-selection__choice" title="Client1">
<span class="select2-selection__choice__remove" role="presentation">×</span>
Client1
</li>
<li class="select2-search select2-search--inline">
<input class="select2-search__field" type="search" tabindex="0"
autocomplete="off" autocorrect="off" autocapitalize="off"
spellcheck="false" role="textbox" aria-autocomplete="list"
placeholder="" style="width: 0.75em;">
</li>
</ul>
I have the jquery script trying to add this but I have not managed to make it work. The code (simplified version) is this one:
function addAll() {
r=$("ul.select2-selection__rendered").empty();
r=$('#id_clients').empty();
stDel='<span class="select2-selection__clear">×</span>';
r=$("span.select2-selection select2-selection--multiple").append(stDel);
stClientList='<li class="select2-selection__choice" title="Client1"><span class="select2-selection__choice__remove" role="presentation">×</span>Client1</li>';
r=$("span.select2-selection select2-selection--multiple").append(stClientList);
stClientId='<option value="2355">Client1</option>';
r=$('#id_clients').append(stClientId);
}
$(document).ready(function(){
$('#id_language').change(function(){
l=$('#id_language').val();
if(l=="ES"){
addAll();
}
});
});
If I use this code the select part is correctly added, but not the ul/li part. If I just run the ul/li part it is added to the field but it is not able to store it. I am not sure which is the correcto way to add values to a field like this. Any ideas or corrections are welcome.