django form ModelChoiceField loads all state names while needed states which are mapped with current selected country
- by Sonu
I am using modelChoiceField to display country and state into address form
class StateSelectionwidget(forms.Select):
""" custom widget to state selection"""
class Media:
js = ('media/javascript/public/jquery-1.5.2.min.js', 'media/javascript/public/countrystateselection.js', )
class AddressForm(forms.Form):
name = forms.CharField(max_length=30)
country = forms.ModelChoiceField(queryset=[])
state = forms.ModelChoiceField(CountryState.objects, widget=StateSelectionwidget)
def __init__(self, *args, **kwargs):
super(AddressForm, self).__init__(*args, **kwargs)
self.fields['country'].queryset = Country.objects.all()
Country model is used to store country names.
CountryState model is used to store all states which is foreign key to Country model
At the time of form loading i am getting all state names in dropdown while i want field to be blank by default.
If name field is empty at the time of form save i am getting error that name can not be empty but also getting all states into dropdown list while i want only the states which are mapped with current selected country.