How to set value to django-select2 field Programmatically (on button click) using javascipt?

706 views Asked by At

In my django app I have a WorkerModel and a ProvinceModel, each worker has a province_id field. I have define a form for Worker using ModelSelect2Widget (django_select2) for province_id. I want to know how to set a value to province_id field using javascript. I have tried with:

$('#id_province_id').val(province_id).trigger('change');

but is not working.Here is the defintion of my form

   from django_select2.forms import ModelSelect2Widget
    class WorkerForm(forms.ModelForm):
        
        class Meta:
            model = WorkerModel
            exclude = ("id",)
            widgets = {
                'name':forms.TextInput(attrs={'class': 'form-control'}),
                'province_id' : ModelSelect2Widget(model=ProvinceModel, queryset=ProvinceModel.objects.filter(),
                                                search_fields=['des_prov__icontains'],
                                                attrs={'style': 'width: 100%;'}),

    }

in the template

   <script>
//on a button click a want to set the value of province_id
     $(document).ready(function () {
    
                $('#id_province_id').djangoSelect2({
                    placeholder: 'Seleccione una opción',
                    escapeMarkup: function (markup) { return markup; },
                    language: {
                        noResults: function () {
                            return "No se encuentran resultados.";
                        }
                    }
    
     });
                });
    </script>
1

There are 1 answers

1
Juan Gabriel Valdés Díaz On

You can try this on your ajax success function:

success: function(data){
   // Assumes that data.result is your proovince id
   if(data.hasOwnProperty('result')){
       $('#id_province_id').val(data.result).trigger('change');
   }
}