Reputation: 59
I am using the django-select2 plugin for a field that lets the user select an institution from a list in the database( driven by AJAX), and it works fine. Here is the field in forms.py
institution = forms.CharField(
widget = ModelSelect2Widget(
queryset=Institution.objects.all(),
attrs={'class': 'form-control'},
model=Institution,
search_fields=['name__icontains'],
max_results=500,
),
Using the same form, the user can edit/change the previous selected Institute. For this, however, I would like to set the initial selected value of the field as the previously selected Institution. This is has caused me a lot of trouble as I am unable to set an initial value for the plugin despite trying many things.
Ideally I am looking to set the initial value of the plugin without using any Javascript(using only Django form options) , something like :
current_instutition = Institution.objects.get(user=page_user)
form.fields['institution'].initial = current_institution
(the above doesn't work)
I've tried using the Select2 placeholder option to set this manually during page load using the following Javascript code:
$("#id_institution").djangoSelect2({
placeholder: {
id: '123',
text: 'My Institution'
}
});
This doesn't seem to do anything at all.(The plugin still loads, with an empty(or no) placeholder) .I'm not sure if django-select2 overrides the manual Select2 options.
Any help is appreciated. Thanks!
Upvotes: 5
Views: 4970
Reputation: 1460
Your institution
field is a CharField
, not a ModelChoiceField
. That is the reason this line is not correct :
form.fields['institution'].initial = current_institution
Upvotes: 1