0

In my django app I have a CenterModel and a ProvinceModel, each center has a province_id field. I have define a form for Center using ModelSelect2Widget (django_select2) for province_id. I want to set the selected value to the province_id field in the template using javascript but the following code is not working:

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

but these lines are not working, they are NOT setting the value to the province_id field. Instead if the field has some previosly selected value the '.val()' funtion clears that value. I double checked and the response.province_id is storing a valid province id. Why I cannot set a value to the selct field? I am working with django-select2==7.7.1

class CenterModel(models.Model):

    name = models.CharField(verbose_name=_("Nombre"), max_length=50, unique=True,blank=False, null=False)

    province_id = models.ForeignKey("ProvinceModel", verbose_name=_("Provincia"),
                                                 blank=True, null=True, on_delete=models.SET_NULL,
                                                 related_name="centers")

    municipality_id = models.ForeignKey("MunicipalityModel", verbose_name=_("Municipio"),
                                                 blank=True, null=True, on_delete=models.SET_NULL,
                                                 related_name="centers")



   
from django_select2.forms import ModelSelect2Widget

class CenterForm(forms.ModelForm):

    class Meta:
        model = CenterModel
        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%;'}),
            'municipality_id' : ModelSelect2Widget(model=MunicipalityModel, queryset=MunicipalityModel.objects.filter(),
                                            search_fields=['municipio__icontains'],
                                            dependent_fields={'province_id': 'cod_prov'},
                                            attrs={'style': 'width: 100%;'}),
            }


class CenterCreateView(LoginRequiredMixin, CreateView):
    model = CenterModel
    context_object_name = 'center'
    template_name = 'riesgo/center/center_form.html'
    form_class = CenterForm

    def get_success_url(self):
        if self.request.method == 'POST' and "_continue" in self.request.POST:
            return reverse('riesgo:center_update', kwargs={'pk': self.object.id})
        elif self.request.session['referer'].get('center',False)  and "centro" not in self.request.session['referer']['center']:
            return self.request.session['referer'].get('center',False) 
        else:
            return reverse_lazy("riesgo:center_detail", kwargs={"pk":self.object.id})   
Ernesto Ruiz
  • 736
  • 9
  • 31
  • Share also your **view**. Or try `$("#id_province_id").val("province_id.pk").trigger("change")` – NKSM Aug 05 '21 at 07:32
  • Also: _Behind the scenes, Django appends "_id" to the field name to create its database column name, see [Django ForeignKey](https://docs.djangoproject.com/en/dev/ref/models/fields/#database-representation)_. – NKSM Aug 05 '21 at 07:33
  • response.province_id is holding a valid integer that represents the id of a province, I also tried $("#id_province_id").val(1).trigger('change'); and is not working, it clears the value of the field. Ht probles is not getting the id of the province cause I am passing the right value, but the val() function is not setting the proper value – Ernesto Ruiz Aug 05 '21 at 15:21

0 Answers0