1

I try to use dependent fields like this:

class AddressForm(forms.Form):
country = forms.ModelChoiceField(
    queryset=Country.objects.all(),
    widget=ModelSelect2Widget(
        model=Country,
        search_fields=['name__icontains'],
    )
)

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

But the City choises are available if no Country is selected. I want to restrict user to select City without selecting Country.

Vit Amin
  • 574
  • 5
  • 20

1 Answers1

-2

From the doc : https://django-select2.readthedocs.io/en/latest/extra.html#chained-select2

Interdependent select2

Also you may want not to restrict the user to which field should be selected first. Instead you want to suggest to the user options for any select2 depending of his selection in another one.

Customize the form in a manner:

class AddressForm(forms.Form):
    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,
        )
    )

You can try to add an initial value for the field in init

def __init__(self,*arg, **kwargs):
    super(AddressForm,self).__init__(*arg, **kwargs)
    self.initial['city'] = ''

If you want to restrict users to select the city you have to do it on the front-end side, there is no way for django to control what people are selecting before you are submiting the form (or you have to make ajax call each time the country change).

If you are considering using another solution, this is how I do it usally(and it does what you want) : https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html

Ben Boyer
  • 1,234
  • 9
  • 14