How to prepopulate the selected choices in HeavySelect2MultipleWidget and ModelMultipleChoiceField
Goal How to pre populate multiple selected choices in HeavySelect2MultipleWidget and in ModelMultipleChoiceField
Problem When form reloaded with validation error, all the pre selected choices will vanish for HeavySelect2MultipleWidget, ModelMultipleChoiceField also not finding a way to pre populate the selected choices when you load update form...
Code Snippet
class RequestRegion(forms.Form):
region = forms.ModelMultipleChoiceField(queryset=Region.objects.all().order_by('region_id'),
widget=Select2MultipleWidget)
class CustReqForm(forms.Form):
#CustomerField(widget=CustomerHeavyWidget(data_view = 'customer_ajax', attrs={'data-minimum-input-length': 4, 'delay':200}))
distributor = forms.CharField(
widget=HeavySelect2MultipleWidget(data_view='customer_ajax',
attrs={'data-minimum-input-length': 4, 'delay':200},
), required=False #queryset=Customer.objects.none()
)
Hello. I also ran into a problem. When you need to edit form data, the transmitted data is not displayed. You have to re-select this data.
I'm having the same issue. Have you been able to solve this in the meanwhile?
Hello. I also ran into a problem. When you need to edit form data, the transmitted data is not displayed. You have to re-select this data.
I am afraid this is a known issue. I would love to see someone come up with a solution tho.
Do you happen to use django-crispyforms? In our case the issue was caused by the combinated use of select2 and crispy forms.
I have the same issue. Deleting django-crispyforms didn't help.
Has been any improvement in this issue?
Select2 want the preselected values as option-elements with selected="selected": https://select2.org/data-sources/ajax#default-pre-selected-values
I did this the following way:
- Make the views get_form add the values I want prepopulated as option values to the ModelSelect2TagWidget of the field: https://github.com/Kagee/homelab-organizer/blob/0dd3b4279fe1320178c92a0c5a01f54a287f7ee1/hlo/views/stockitems.py#L167
- Override create_option in the widget to always set selected to "selected", as i could not get anaything like initial values to work. This will work as all the options are the options from step 1. that we want selected: https://github.com/Kagee/homelab-organizer/blob/0dd3b4279fe1320178c92a0c5a01f54a287f7ee1/hlo/forms.py#L18
If anyone have any better suggestions after seeing my workaround, please share.