0

I am new to this field. I am working on Dependent Dropdowns for which i took reference from here. On replicating the same with the following code:

Forms.py

class AddressForm(forms.ModelForm):
   class Meta:
       model=City
       country = forms.ModelChoiceField(
          queryset=Country.objects.all(),
          label=u"Country",
          widget= ModelSelect2Widget(
            search_fields=['name__icontains'],
            dependent_fields={'city': 'cities'},
           )
       )

   city = forms.ModelChoiceField(
       queryset=City.objects.all(),
       label=u"City",
       widget=ModelSelect2Widget(
           search_fields=['name__icontains'],
           dependent_fields={'country': 'country'},
           max_results=500,
       )
   )

Getting error

Undefined variable: 'ModelSelect2Widget'

I also installed:

INSTALLED_APPS=[
                'django_select2',
                'django_q',
  ]
2
  • Have you imported ModelSelect2Widget? Commented Jan 4, 2021 at 12:07
  • hey @WBM I tried- from django_select2 import ModelSelect2Widget but At the time of running server its giving error cannot import name 'ModelSelect2Widget' I hope my method is correct Commented Jan 4, 2021 at 12:29

1 Answer 1

0

The problem is in your import. In Select2, the ModelSelect2Widget class is in the forms module. So your import should be as follows:

from django_select2.forms import ModelSelect2Widget


class AddressForm(forms.ModelForm):
   class Meta:
       model=City
       country = forms.ModelChoiceField(
          queryset=Country.objects.all(),
          label=u"Country",
          widget= ModelSelect2Widget(
            search_fields=['name__icontains'],
            dependent_fields={'city': 'cities'},
           )
       )

   city = forms.ModelChoiceField(
       queryset=City.objects.all(),
       label=u"City",
       widget=ModelSelect2Widget(
           search_fields=['name__icontains'],
           dependent_fields={'country': 'country'},
           max_results=500,
       )
   )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.